Go by Example

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 a ready-to-use struct whose fields each have their type's default value, such as 0, false or an empty string.

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 starting state. See Struct Embedding to learn how one struct can expose fields and methods from another.

Enjoyed this? Get more software craft delivered to your inbox.