Golang Struct - Getting Started with Golang

Опубликовано: 07 Март 2025
на канале: Maharlikans Code
142
6

In this Getting Started with Golang, we will learn how to use the Golang Structs which is the collection of fields that can hold multiple field types, exportable or non-exportable struct fields or even the struct name by itself in Golang programming language with step by step guide.

#MaharlikansCode
#GolangStructs
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode

Source Codes:
package main

import (
"errors"
"fmt"
"strings"
)

// Person is the collections of personal information
type Person struct {
FirstName, LastName string
Age int // Age is the person's age
UserEmail Email
}

// Email is the collection of user's email information
type Email struct {
Name, Address string
}

func main() {
p := &Person{
FirstName: "John",
LastName: "Doe",
Age: 25,
UserEmail: Email{"John Doe", "[email protected]"},
}
fmt.Println("FirstName: ", p.FirstName)
fmt.Println("UserEmail: ", p.UserEmail.Address)

np, err := newPerson("Jose", "Rambo", 17, Email{"Jose Rambo", "[email protected]"})
if err != nil {
fmt.Println("Oops!, got some error: ", err)
return
}
fmt.Println("first name from newPerson: ", np.FirstName)
}

func newPerson(firstName, lastName string, age int, em Email) (*Person, error) {
if len(strings.TrimSpace(firstName)) == 0 {
return &Person{}, errors.New("Please enter your first name")
}
if len(strings.TrimSpace(lastName)) == 0 {
return &Person{}, errors.New("Please enter your last name")
}
if age less than or equal to 18 {
return &Person{}, errors.New("You must be at least 18 years old to keep your record")
}
return &Person{
FirstName: firstName,
LastName: lastName,
Age: age,
UserEmail: em,
}, nil
}