Go Structs

What is a Struct?

A struct in Go is a collection of fields. It allows you to define custom data types and model real-world entities.

type Person struct {
    Name string
    Age  int
}

Creating Structs

p1 := Person{Name: "Alice", Age: 30}
p2 := Person{"Bob", 25} // order matters
var p3 Person            // zero-valued fields

Fields of a struct get default values if not initialized.

Accessing Fields

fmt.Println(p1.Name)
p1.Age = 31

Pointers to Structs

You can use a pointer to a struct to modify it efficiently:

func birthday(p *Person) {
    p.Age++
}

No need to use (*p).Field — Go lets you use p.Field directly with pointers.

Structs in Slices

people := []Person{
    {Name: "Ava", Age: 22},
    {Name: "Ben", Age: 28},
}

Useful for building record lists, table rows, etc.

Anonymous Structs

book := struct {
    Title string
    Pages int
}{"Go in Action", 300}

Good for one-time usage without a named type.

Struct Tags

Struct fields can include tags, often used for JSON or DB mapping:

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

Packages like encoding/json use these for marshaling.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic