Structs, literals and anonymous structs
A struct is a type that groups named fields, and it is the closest thing Go has to a record. It is a value type: assigning it copies every field, passing it to a function copies it again, and a field holds the value that was put there, not a reference to it. The arrays lesson showed the same copy rule for a fixed-size collection; a struct is the version whose elements have names.
Fields and literals
A struct type declares fields with a name and a type, and several fields may share one line. A literal without field names lists every field in order and must list all of them; a literal with names may set any subset, and the rest take their zero value. Keyed literals are the ones to write in a library, because a new field does not break them.
package main
import "fmt"
type point struct {
X, Y int
}
func main() {
positional := point{1, 2}
keyed := point{Y: 5}
empty := point{}
fmt.Printf("%v %+v %+v\n", positional, keyed, empty)
fmt.Println("X of keyed:", keyed.X, "Y:", keyed.Y)
positional.X = 10
fmt.Println("sum:", positional.X+positional.Y)
}
go run literal.go
{1 2} {X:0 Y:5} {X:0 Y:0}
X of keyed: 0 Y: 5
sum: 12
The empty literal printed {0 0}: a struct always exists, with zero fields, which is why it needs no constructor. The zero value is a usable value when the fields are designed for it, and that is a design decision, not a language rule.
A struct is copied
The assignment and the function argument both copy. A function that takes a struct and changes a field changes its own copy; a function that must change the caller's value takes a pointer, which the pointers lesson introduced. A copy is cheap for a small struct and expensive for a large one, and the compiler decides how it is passed without telling the program.
package main
import "fmt"
type config struct {
name string
retries int
}
func bump(c config) config {
c.retries++
return c
}
func bumpPointer(c *config) {
c.retries++
}
func main() {
c := config{name: "api", retries: 1}
bumped := bump(c)
bumpPointer(&c)
fmt.Println("original:", c)
fmt.Println("returned:", bumped)
}
go run copy.go
original: {api 2}
returned: {api 2}
The returned copy went to 2 and the original is 2 as well, for two different reasons: bump returned a changed copy, and bumpPointer changed the caller's value through its address. A method on a value receiver has exactly the copy rule of a function, which is the subject of the next lesson.
Anonymous and nested structs
A struct type can be written where a value is needed, with no name at all. That is the right tool for a table inside one function, for a test case, and for the body of a JSON request that no other code touches. A named type is better as soon as the value crosses a function boundary, because a name is what documentation and error messages can refer to.
package main
import "fmt"
func main() {
rows := []struct {
Name string
Score int
}{
{"ada", 91},
{"grace", 88},
}
for _, row := range rows {
fmt.Printf("%-6s %3d\n", row.Name, row.Score)
}
nested := struct {
Title string
Meta struct {
Author string
Year int
}
}{Title: "Go"}
nested.Meta = struct {
Author string
Year int
}{"ada", 2009}
fmt.Printf("%+v\n", nested)
}
go run anon.go
ada 91
grace 88
{Title:Go Meta:{Author:ada Year:2009}}
The nested anonymous type had to be repeated when the field was assigned, which is the price of not naming it: a name would have made the second literal shorter. A struct that is assigned from another struct needs the same type, and two anonymous types with the same fields are the same type only when they are written identically.
Comparison and map keys
A struct is comparable when every field is comparable, and then == compares the fields in order. Comparable structs work as map keys, which is how a grid or a composite index is written without joining the parts into a string. Slices, maps and functions are not comparable, so a struct that holds one is not comparable either.
package main
import "fmt"
type point struct {
X, Y int
}
func main() {
a := point{1, 2}
b := point{1, 2}
c := point{1, 3}
fmt.Println("a == b:", a == b, "a == c:", a == c)
grid := map[point]string{{0, 0}: "origin", {1, 0}: "east"}
grid[point{0, 1}] = "north"
fmt.Println("at origin:", grid[point{X: 0, Y: 0}], "len:", len(grid))
}
go run compare.go
a == b: true a == c: false
at origin: origin len: 3
The map found the origin with a fresh literal because the key compares by value. The compiler refuses the same comparison as soon as one field is a slice:
package main
import "fmt"
type record struct {
name string
tags []string
}
func main() {
a := record{name: "x"}
b := record{name: "x"}
fmt.Println(a == b)
}
go build -o slicefield slicefield.go
# command-line-arguments
./slicefield.go:13:14: invalid operation: a == b (struct containing []string cannot be compared)
The message names the type and the field type. The answer is slices.Equal for the slice field, or a comparison of a stable key such as an id, not a hand-written loop that forgets a field.
Exercises
- Define an order struct with a customer, three line items and a total, and print it with %+v and with a table written by hand.
- Write a function that takes a point by value and one that takes a pointer, both moving the point by one. Print the caller's point after each call.
- Use a struct of two integers as a map key to store a chessboard. Why does a struct of two slices not work as the same key?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the zero value of a struct?
Answer
A value whose every field is the zero value of its type
A struct is a value, so it always exists; the fields start at their own zero values.
-
What does the first line of this program print?
package main import "fmt" type point struct { X, Y int } func main() { positional := point{1, 2} keyed := point{Y: 5} empty := point{} fmt.Printf("%v %+v %+v\n", positional, keyed, empty) fmt.Println("X of keyed:", keyed.X, "Y:", keyed.Y) positional.X = 10 fmt.Println("sum:", positional.X+positional.Y) }Answer
{1 2} {X:0 Y:5} {X:0 Y:0} / X of keyed: 0 Y: 5 / sum: 12
%v prints values only, and %+v adds the field names to every struct it prints.
-
What does a keyed literal allow that a positional one does not?
Answer
Setting a subset of the fields in any order
A keyed literal names the fields it sets; a positional literal must list all of them in order.
-
What does this program print?
package main import "fmt" type config struct { name string retries int } func bump(c config) config { c.retries++ return c } func bumpPointer(c *config) { c.retries++ } func main() { c := config{name: "api", retries: 1} bumped := bump(c) bumpPointer(&c) fmt.Println("original:", c) fmt.Println("returned:", bumped) }Answer
original: {api 2} / returned: {api 2}
bump changed a copy and returned it; bumpPointer changed the original through its address.
-
When can a struct be compared with ==?
Answer
When every field type is comparable
Slices, maps and functions are not comparable, so a struct holding one is not comparable either.
-
What does this program print?
package main import "fmt" type point struct { X, Y int } func main() { a := point{1, 2} b := point{1, 2} c := point{1, 3} fmt.Println("a == b:", a == b, "a == c:", a == c) grid := map[point]string{{0, 0}: "origin", {1, 0}: "east"} grid[point{0, 1}] = "north" fmt.Println("at origin:", grid[point{X: 0, Y: 0}], "len:", len(grid)) }Answer
a == b: true a == c: false / at origin: origin len: 3
Comparable structs compare by field, and a struct key finds the entry with an equal literal.
-
What does the compiler say about this program?
package main import "fmt" type record struct { name string tags []string } func main() { a := record{name: "x"} b := record{name: "x"} fmt.Println(a == b) }Answer
invalid operation: a == b (struct containing []string cannot be compared)
A slice is not comparable, so the struct that holds one is not comparable.
-
Which value is a good anonymous struct?
Answer
A row of a table used only inside one function
Anonymous types are local conveniences; a name serves documentation, errors and methods.
-
What does the last line of this program print?
package main import "fmt" func main() { rows := []struct { Name string Score int }{ {"ada", 91}, {"grace", 88}, } for _, row := range rows { fmt.Printf("%-6s %3d\n", row.Name, row.Score) } nested := struct { Title string Meta struct { Author string Year int } }{Title: "Go"} nested.Meta = struct { Author string Year int }{"ada", 2009} fmt.Printf("%+v\n", nested) }Answer
ada 91 / grace 88 / {Title:Go Meta:{Author:ada Year:2009}}
%+v prints the field names of the outer struct, and of the nested one as well.
-
What does passing a struct to a function do?
Answer
Copies the whole struct
Structs are values; a function that must change the caller's copy takes a pointer.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev