Define a new type struct
type Person struct {
Name string
Age int
}
Declaring them
girl := &Person{}
Or shorter with the keyword new
girl := new(Person)
Kind of self
You can define “structure” to create your own type
type Person struct {
Name string
Age int
}
// Function with weird syntax, work like "self" in other language
func (p *Person) SayHello() {
fmt.Println("Hello", p.Name)
}
func main() {
// use pointer with struct
girl := new(Person)
girl.Name = "Alice"
girl.SayHello()
}
Function returning structure
You can create structure, generating them in function and returning to your main():
$EDITOR pkg/person/check.go
package person
type MyPerson struct {
Name string
Age int
}
func Build() (*MyPerson, error) {
newperson := &MyPerson{} // same with new(MyPerson)
newperson.Name = "Bob"
newperson.Age = 10
return newperson, nil
}
$EDITOR cmd/<name>/main.go
func main() {
myPerson, err := person.Build()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(myPerson.Name)
fmt.Println(myPerson.Age)
}