Structs and composite literals
- Version
- 1.27
- Review
- Draft
Summary#
A struct groups named fields. Fields omitted from a keyed literal get zero values. Assigning a struct copies its fields. Structs compare with == when all field types are comparable.
Syntax#
type Book struct {
Title string
Year int
}
book := Book{Title: "Dune"}
Example#
package main
import "fmt"
type book struct {
title string
year int
}
func main() {
var blank book
original := book{title: "Dune", year: 1965}
fmt.Printf("%+v\n", blank)
duplicate := original // copies both fields
fmt.Println(original == duplicate)
duplicate.year = 2000
fmt.Println(original.year, duplicate.year, original == duplicate)
ref := &original
ref.year = 1966 // shorthand for (*ref).year
fmt.Println(original.year)
copies := map[book]int{original: 2}
fmt.Println(copies[book{title: "Dune", year: 1966}])
point := struct{ x, y int }{x: 3, y: 4}
fmt.Println(point)
}
Expected output#
{title: year:0}
true
1965 2000 false
1966
2
{3 4}
Common mistakes#
A struct copy is shallow. Slice, map and pointer fields in both copies can still refer to the same data. Prefer keyed literals. A nonempty positional literal must list every field in declaration order. If a struct contains interface fields, comparing two values can panic when the corresponding fields hold the same uncomparable dynamic type.
Version applicability#
The syntax and example work from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0