Skip to content
AgileLogics
5 min read

Structs

Prerequisites: Multiple return values & errors

A struct groups related values (called fields) into one type. Go has no classes — structs, plus the methods you'll attach to them shortly, fill that role.

Syntax

type Person struct {
    Name string
    Age  int
}

p := Person{Name: "Ada", Age: 36} // named fields (preferred)
q := Person{"Alan", 41}           // positional: all fields, in order
var r Person                      // zero value: {"" 0}

Field names follow the same visibility rule as everything else: an uppercase first letter (Name) is exported outside the package; lowercase (name) is private to the package.

Example

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    ada := Person{Name: "Ada", Age: 36}
    fmt.Println(ada.Name)

    ada.Age = 37
    fmt.Println(ada)
    fmt.Printf("%+v\n", ada)

    var unknown Person
    fmt.Printf("%+v\n", unknown)

    twin := ada // copies every field
    twin.Name = "Twin"
    fmt.Println(ada.Name, twin.Name)

    fmt.Println(ada == Person{Name: "Ada", Age: 37})

    people := []Person{
        {Name: "Grace", Age: 85},
        {Name: "Linus", Age: 54},
    }
    for _, person := range people {
        fmt.Println(person.Name, "is", person.Age)
    }
}

Expected output

Ada
{Ada 37}
{Name:Ada Age:37}
{Name: Age:0}
Ada Twin
true
Grace is 85
Linus is 54

Like arrays, structs are values: assigning or passing one copies all of its fields. Two structs can be compared with == when all their fields are comparable.

Common mistakes

  • Mixing named and positional fields in one literal — not allowed.
  • Using positional literals for structs that may gain fields later; adding a field breaks every positional literal.
  • Expecting a change to a copy (or to the loop variable in for _, p := range people) to update the original. Modify people[i].Age by index instead.

Practice

Define a Book struct with Title, Author, and Pages fields. Create two books in a slice, print each with %+v, and print the total number of pages.

Show solution
package main

import "fmt"

type Book struct {
    Title  string
    Author string
    Pages  int
}

func main() {
    books := []Book{
        {Title: "Dune", Author: "Frank Herbert", Pages: 412},
        {Title: "Emma", Author: "Jane Austen", Pages: 474},
    }

    total := 0
    for _, b := range books {
        fmt.Printf("%+v\n", b)
        total += b.Pages
    }
    fmt.Println("Total pages:", total) // 886
}