Structs

Introduction

So far every value in your programs has been a single number, a string or a list. Real things are described by several values together: a student has a name, an age and a mark; a point on a map has an x and a y. You could keep these in separate variables, but then it is easy to mix them up. Go lets you define your own type that groups them. This is called a struct. Structs are the building blocks of Go programs, and the next lessons add behaviour to them with methods and interfaces.

How it works

A struct type is declared with type, a name and the word struct, followed by the fields in braces:

type Person struct {
	Name string
	Age  int
}

Create a value with a composite literal. Always name the fields; it is clear and it still works when you add a new field later:

p := Person{Name: "Ada", Age: 36}

Fields you leave out get their zero value, so Person{Name: "Bob"} has Age 0, and var q Person has an empty name and age 0. Read and change a field with a dot: p.Age = 37.

A struct can contain another struct, as a normal field, such as Center Point inside a circle. You can also embed a type by writing only its name; the fields of the inner type can then be used directly on the outer value. In this course, normal named fields are the clearest choice.

Structs are values. When you assign a struct to another variable or pass it to a function, the whole struct is copied, so changing the copy does not change the original. Two structs of the same type are equal with == when all their fields are equal.

Structs are often kept in slices: people := []Person{...}, and then for _, p := range people goes through them. Remember that p is a copy; to change the item in the slice, use the index: people[i].Age++. To sort a slice of structs by a field, use sort.Slice with a function that says which of two items comes first:

sort.Slice(people, func(i, j int) bool {
	return people[i].Age < people[j].Age
})

For printing, %v shows the values, {Ada 36}, and %+v also shows the field names, {Name:Ada Age:36}. Field names that begin with a capital letter are visible outside the package; lower case ones are private. Inside one program both work, and the course uses capitals for clarity.

Example

package main

import (
	"fmt"
	"sort"
)

type Point struct {
	X, Y int
}

type Person struct {
	Name string
	Age  int
	Home Point
}

func main() {
	p := Person{Name: "Ada", Age: 36}
	p.Home.X = 5
	fmt.Println(p)
	fmt.Printf("%+v\n", p)

	q := p
	q.Age = 40
	fmt.Println(p.Age, q.Age, p == q)

	var empty Person
	fmt.Printf("%q %d\n", empty.Name, empty.Age)

	people := []Person{
		{Name: "Cy", Age: 29},
		{Name: "Bo", Age: 51},
		{Name: "Di", Age: 17},
	}
	people[0].Age++
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	for _, person := range people {
		fmt.Println(person.Name, person.Age)
	}
}

Line by line

  1. Point and Person are new types. Person has a Home field of type Point, which shows nesting.
  2. Person{Name: "Ada", Age: 36} uses named fields; the missing Home gets its zero value.
  3. p.Home.X = 5 changes a field of the nested struct.
  4. q := p copies the whole struct, so changing q.Age leaves p as it was.
  5. p == q is false because the ages now differ.
  6. A slice of Person is sorted by age with sort.Slice, and %v and %+v print the values.

Expected result

{Ada 36 {5 0}}
{Name:Ada Age:36 Home:{X:5 Y:0}}
36 40 false
"" 0
Di 17
Cy 30
Bo 51

In the real world

Almost every program has structs: an order with an id, a customer and a list of items; a configuration with host, port and timeout; a log entry with a time and a message. When a Go program reads JSON from a web service, it turns the text into a struct, and when it sends data back it turns a struct into JSON. Good struct design makes the rest of the program easier to write.

Common mistakes

  • Using positional literals such as Person{"Ada", 36}. They break as soon as a field is added.
  • Changing the loop variable of range and expecting the slice to change. It is a copy.
  • Forgetting that assignment copies a struct completely.
  • Comparing structs that contain slices with ==; this does not compile.
  • Putting a comma problem in a literal. In a multi-line literal every line, including the last, needs a trailing comma.

Best practices

  • Name fields clearly and group only values that belong together.
  • Create structs with named fields.
  • Keep structs small, and put behaviour in methods, which come in the next lesson.

Summary

A struct groups named fields into your own type. Create values with named fields, read and change fields with a dot, and nest structs or keep them in slices. A struct is copied when assigned or passed, equal structs have equal fields, and %v and %+v print them.

Quick check

1. How do you read the Name field of a Person value p?
2. What is the value of the Age field in Person{Name: "Bob"}?
3. What does q := p do when p is a struct?
4. How do you change the third struct in a slice people?
5. What does %+v add compared with %v?

Key takeaways

  • A struct groups related fields into one type: type Person struct { Name string; Age int }.
  • Create one with named fields, Person{Name: "Ada", Age: 36}, and read fields with a dot.
  • Structs are copied when assigned or passed to a function, and two structs are equal when all their fields are.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.