Structs in Go

Posted by yhuang
Public (Editable by Users)

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

Go
Edit
package main

import "fmt"

// Define a struct.
type person struct {
    name string
    age  int
}

// This function initializes a struct variable and returns a pointer to it.
func NewPerson(name string) *person {
    p := person{name: name}
    p.age = 42
    return &p
}

func main() {
    // Without keys, you can initialize the members in order that they were defined.
    fmt.Println(person{"Bob", 20})
    
    // With keys.
    fmt.Println(person{name: "Alice", age: 30})

    // Omitted members will be initialized with their "zero value".
    fmt.Println(person{name: "Fred"})

    // Returning a pointer to an initialized struct.
    fmt.Println(&person{name: "Ann", age: 40})

    // Calling a function to create our struct.
    fmt.Println(NewPerson("Jon"))

    // Using the dot operator to access the member values. Works with values and pointers.
    s := person{name: "Sean", age: 50}
    fmt.Println(s.name)

    sp := &s
    fmt.Println(sp.age)

    sp.age = 51
    fmt.Println(sp.age)
}