Skip to content
Codewilds

Lesson 21 of 38 · Structs & Methods

Go Structs: Define Your Own Types

easy10 XP5 min read

So far your data has lived in single values, slices and maps. But programs are usually about things — players, orders, books — and each thing has several properties at once. Keeping a book's title, author and year in three separate variables (or three slices that must stay in sync) gets messy fast.

A struct bundles related values into one new type. Go has no classes: structs, together with the methods you'll attach to them later in this chapter, are how you model data in Go.

Declaring a struct type

type Player struct {
	Name  string
	Level int
	HP    int
}

type Player struct { ... } declares a new type called Player. Each line inside is a field: a name followed by a type. Fields of the same type may share a line, as in Level, HP int. Names that start with a capital letter are exported (visible to other packages); lowercase ones stay private to their package.

Struct literals and zero values

package main

import "fmt"

type Player struct {
	Name  string
	Level int
	HP    int
}

func main() {
	ada := Player{Name: "Ada", Level: 3, HP: 80}
	bo := Player{Name: "Bo"} // Level and HP get zero values
	var nobody Player        // every field is a zero value

	fmt.Println(ada)
	fmt.Printf("%+v\n", bo)
	fmt.Printf("%+v\n", nobody)

	ada.Level++ // read and write fields with a dot
	fmt.Println(ada.Name, ada.Level)
}
{Ada 3 80}
{Name:Bo Level:0 HP:0}
{Name: Level:0 HP:0}
Ada 4

A struct literal such as Player{Name: "Ada", ...} creates a value. Every field you leave out gets its zero value, and a struct declared with var is zero all the way through — an empty name, level 0, HP 0 — so it is always safe to use. %v prints only the values; %+v adds the field names, which helps when debugging.

Go also accepts positional literals like Player{"Ada", 3, 80}, but avoid them for your own types. You must list every field in declaration order, and as soon as someone adds or reorders a field, every positional literal breaks — or, worse, silently puts a value into the wrong field of the same type. Named fields are clearer and survive changes.

Nested and anonymous structs

A field can itself be a struct. Chain the dots to reach inside:

type Address struct {
	City    string
	Country string
}

type Customer struct {
	Name    string
	Address Address
}

c := Customer{
	Name:    "Ann",
	Address: Address{City: "Lisbon", Country: "Portugal"},
}
c.Address.City = "Porto"
fmt.Printf("%+v\n", c)
{Name:Ann Address:{City:Porto Country:Portugal}}

Note the comma after the last field of a multi-line literal: Go requires it.

When you need a type only once, you can skip its name. An anonymous struct declares the type and the value in one go, which is popular for small test tables:

point := struct {
	X, Y int
}{X: 3, Y: 4}
fmt.Println(point) // {3 4}

Structs are values

Assigning a struct copies all of its fields, and passing it to a function does the same. Changing the copy never touches the original:

a := Player{Name: "Ada", Level: 1}
b := a // b is an independent copy
b.Level = 99
fmt.Println(a.Level, b.Level) // 1 99

c := Player{Name: "Ada", Level: 1}
fmt.Println(a == c, a == b) // true false

Structs can be compared with == when all their fields are comparable: two struct values are equal when every field is equal. A struct that contains a slice or a map can't be compared that way. (To let a function change your struct, you'll use pointers in the next lesson.)

Constructors and slices of structs

Go has no constructors. By convention you write a function named NewX that returns a ready-to-use value with sensible defaults:

// NewPlayer returns a level-1 player with full health.
func NewPlayer(name string) Player {
	return Player{Name: name, Level: 1, HP: 100}
}

Structs fit naturally into slices. Loop with an index when you want to change the elements:

team := []Player{NewPlayer("Ada"), NewPlayer("Bo")}
for i := range team {
	team[i].HP -= 10 // changes the element inside the slice
}
fmt.Println(team) // [{Ada 1 90} {Bo 1 90}]

Common mistakes

  • Positional literals for your own types break (or silently mix up fields) when the struct changes. Name the fields.
  • Changing the loop copy: in for _, p := range team { p.HP -= 10 }, p is a copy of each element, so the slice doesn't change. Write team[i].HP -= 10.
  • Expecting a function to modify a struct argument: it receives a copy. Return the updated struct instead (or use a pointer — next lesson).
  • Comparing structs that contain slices or maps with ==: the compiler rejects it (struct containing []string cannot be compared). Compare the fields you care about instead.

Assignment

The Guild library needs a catalogue. The Book type is already declared for you:

type Book struct {
	Title, Author string
	Year, Pages   int
}

Write four functions:

  1. NewBook(title, author string, year int) Book returns a Book with the given title, author and year, and Pages set to 100 (a placeholder until someone counts them). If author is empty, use "Unknown".
  2. IsClassic(b Book) bool reports whether the book was published before 1950.
  3. Summary(b Book) string returns "<Title> by <Author> (<Year>)", for example "Dune by Frank Herbert (1965)".
  4. Oldest(books []Book) Book returns the book with the smallest Year. If several books share that year, return the first of them. For an empty slice, return the zero value Book{}.
dune := NewBook("Dune", "Frank Herbert", 1965)
fmt.Println(dune)            // {Dune Frank Herbert 1965 100}
fmt.Println(Summary(dune))   // Dune by Frank Herbert (1965)
fmt.Println(IsClassic(dune)) // false

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Classes, objects and structs in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+10 XP

Lesson 21 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.