Structs
Defining a struct, naming its fields, creating values, and understanding zero values.
A struct groups named fields into one value. Its zero value is ready to use, with each field set to that field type's zero value.
Use named fields in literals so the values stay clear when the field order changes:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
var unknown Person
alice := Person{Name: "Alice", Age: 30}
alice.Age++
fmt.Println(unknown) // { 0}
fmt.Println(alice.Name, alice.Age) // Alice 31
}In production
Prefer the zero value when it represents a valid initial state. Use Struct Embedding when a type intentionally promotes another type's fields or methods.
Enjoyed this? Get more software craft delivered to your inbox.