Lesson 8 of 20 · Part 2: Working with data
Structs
Learn Go structs for beginners. Define your own types, create and update struct values, nest structs, use slices of structs, compare and sort them.
3 min read · Updated · Beginner friendly
What you'll learn
- Define a struct type and create values of it
- Read and update fields, and understand that structs are copied
- Nest structs and keep lists of structs in slices and maps
- Compare structs and sort a slice of structs
So far every value has been a single number, string or list. Real things have several properties at once: a book has a title, an author and a page count; a user has a name, an email and an age. A struct groups related values, called fields, into a single new type that you design.
Go has no classes. Structs, together with the methods you’ll add in lesson 12, fill that role.
Defining a struct type
package main
import "fmt"
type Book struct {
Title string
Author string
Pages int
}
func main() {
b := Book{Title: "The Gopher Guide", Author: "Ada", Pages: 320}
fmt.Println(b)
fmt.Printf("%+v\n", b) // %+v also prints the field names
fmt.Println(b.Title, "has", b.Pages, "pages")
}{The Gopher Guide Ada 320}
{Title:The Gopher Guide Author:Ada Pages:320}
The Gopher Guide has 320 pagestype Book struct { ... }creates a new type calledBook.- Each line inside lists a field name and its type.
- You read and write fields with a dot:
b.Title. - Type definitions usually go at the top level of the file, outside
main.
Creating struct values
There are a few ways to create a struct value:
package main
import "fmt"
type Point struct {
X, Y int // two fields of the same type on one line
}
func main() {
p1 := Point{X: 3, Y: 4} // with field names (recommended)
p2 := Point{Y: 10} // fields you leave out get their zero value
var p3 Point // all fields are zero
p4 := Point{7, 8} // positional: values in field order
fmt.Println(p1, p2, p3, p4)
p3.X = 5 // update a field
fmt.Println(p3)
}{3 4} {0 10} {0 0} {7 8}
{5 0}Prefer field names
Positional values like Point{7, 8} break as soon as someone adds or reorders a field. Writing Point{X: 7, Y: 8} is clearer and safer, and it is what most Go code does.
Structs are copied
Assigning a struct to another variable copies all of its fields. The two variables are then completely independent:
package main
import "fmt"
type Player struct {
Name string
Score int
}
func main() {
a := Player{Name: "Ada", Score: 10}
b := a // b is a copy
b.Score = 99
fmt.Println("a:", a.Score, "b:", b.Score)
}a: 10 b: 99This is different from maps (lesson 7), which are shared. If you want several parts of a program to change the same struct, you share a pointer to it. Lesson 10 explains pointers.
Nested structs
A field can itself be a struct. This lets you build bigger types out of smaller ones:
package main
import "fmt"
type Address struct {
City string
Country string
}
type Customer struct {
Name string
Email string
Address Address
}
func main() {
c := Customer{
Name: "Grace",
Email: "grace@example.com",
Address: Address{
City: "Pune",
Country: "India",
},
}
fmt.Println(c.Name, "lives in", c.Address.City)
c.Address.City = "Mumbai"
fmt.Printf("%+v\n", c)
}Grace lives in Pune
{Name:Grace Email:grace@example.com Address:{City:Mumbai Country:India}}Slices and maps of structs
Most programs keep many values of a struct type in a slice or a map:
package main
import "fmt"
type Task struct {
Title string
Done bool
}
func main() {
tasks := []Task{
{Title: "Install Go", Done: true},
{Title: "Learn structs", Done: false},
{Title: "Build a project", Done: false},
}
tasks[1].Done = true // update an element in place through its index
remaining := 0
for _, t := range tasks {
mark := " "
if t.Done {
mark = "x"
} else {
remaining++
}
fmt.Printf("[%s] %s\n", mark, t.Title)
}
fmt.Println(remaining, "task(s) left")
}[x] Install Go
[x] Learn structs
[ ] Build a project
1 task(s) leftInside a slice literal you can leave out the type name for each element: {Title: ...} instead of Task{Title: ...}.
Anonymous structs
For a one-off group of values you can use a struct without giving the type a name. This is handy for small tables of test data:
package main
import "fmt"
func main() {
cases := []struct {
input string
want int
}{
{"go", 2},
{"gopher", 6},
}
for _, c := range cases {
fmt.Println(c.input, len(c.input) == c.want)
}
}go true
gopher trueYou will see exactly this pattern again in table-driven tests in lesson 19.
Comparing structs
Two struct values are equal with == when all their fields are equal (as long as every field type can be compared):
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
a := Point{1, 2}
b := Point{1, 2}
c := Point{2, 1}
fmt.Println(a == b, a == c)
visited := map[Point]bool{a: true} // comparable structs can be map keys
fmt.Println(visited[b], visited[c])
}true false
true falseSorting a slice of structs
To sort structs you have to say which field to sort by. slices.SortFunc takes a small comparison function, written inline. Don’t worry about the function syntax yet; lesson 9 explains it. Just read it as “compare a and b by their Age”:
package main
import (
"cmp"
"fmt"
"slices"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{
{"Ada", 36},
{"Linus", 21},
{"Grace", 45},
}
slices.SortFunc(people, func(a, b Person) int {
return cmp.Compare(a.Age, b.Age)
})
for _, p := range people {
fmt.Println(p.Name, p.Age)
}
}Linus 21
Ada 36
Grace 45cmp.Compare returns a negative number, zero or a positive number, which tells the sort which value comes first. To sort from oldest to youngest, swap a and b.
Exported and unexported fields
Field names follow the same rule as everything else in Go: a name starting with a capital letter is exported and can be used by other packages. A lowercase field is private to its package. This matters later, for example when converting structs to JSON, which only includes exported fields (lesson 18).
Exercises
1. A rectangle. Define a Rectangle struct with Width and Height (float64). Create one that is 3.5 by 2 and print its area and perimeter.
Show solution
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func main() {
r := Rectangle{Width: 3.5, Height: 2}
fmt.Println("area:", r.Width*r.Height)
fmt.Println("perimeter:", 2*(r.Width+r.Height))
}area: 7
perimeter: 11In lesson 12 you will turn Area and Perimeter into methods on Rectangle.
2. Library report. Make a slice of three Book values (title, author, pages). Print the total number of pages and the title of the longest book.
Show solution
package main
import "fmt"
type Book struct {
Title string
Author string
Pages int
}
func main() {
books := []Book{
{Title: "Short Stories", Author: "Ken", Pages: 120},
{Title: "The Big Novel", Author: "Rob", Pages: 640},
{Title: "Go Recipes", Author: "Ada", Pages: 300},
}
total := 0
longest := books[0]
for _, b := range books {
total += b.Pages
if b.Pages > longest.Pages {
longest = b
}
}
fmt.Println("total pages:", total)
fmt.Println("longest:", longest.Title)
}total pages: 1060
longest: The Big Novel3. Sort by name. Take the people slice from the sorting example and sort it alphabetically by Name instead.
Show solution
package main
import (
"cmp"
"fmt"
"slices"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"Linus", 21}, {"Ada", 36}, {"Grace", 45}}
slices.SortFunc(people, func(a, b Person) int {
return cmp.Compare(a.Name, b.Name)
})
fmt.Println(people)
}[{Ada 36} {Grace 45} {Linus 21}]Recap
type Name struct { ... }defines your own type made of named fields.- Create values with
Name{Field: value}; missing fields get zero values. - Assigning a struct copies it; use pointers (lesson 10) to share one.
- Structs can be nested, stored in slices and maps, compared with
==and sorted withslices.SortFunc. - Capitalised fields are exported; lowercase fields are private to the package.
That completes Part 2. Next, in Part 3, you will write your own functions.
Finished this lesson?
Your progress is saved in this browser only.