Lesson 14 · 14 of 20
Structs · Go
Group related data into a Go struct: fields, literals by name or by order, %+v, copies and slices of structs.

A struct gathers several related pieces of data into a new type. type Book struct defines a book with four fields: Title and Author, strings (they share a type and sit on one line), Pages, an integer, and Read, a boolean. The names start with a capital letter, as is the Go habit for anything shared with other packages.
A book is created with a literal. With names, Book{Title: "Emma", ...}, you can leave fields out and they take their zero value: Read stays false. Without names you must give them all, in the order of the definition, as with tale.
The dot reads and changes a field: novel.Read = true. fmt.Println prints the values between braces, and %+v adds each field's name, which is very handy for debugging.
Assigning a struct copies it, as with arrays: changing gift.Title does not change tale. A slice of structs, []Book, makes a small bookshelf; inside the literal you need not repeat Book for each element. The for prints each book in columns and adds up the pages: 1132.
Code · main.go
package mainimport "fmt"// A struct groups related fields into one type.type Book struct { Title, Author string Pages int Read bool}func main() { // Fields by name; the missing ones take their zero value. novel := Book{Title: "Emma", Author: "Jane Austen", Pages: 474} tale := Book{"Matilda", "Roald Dahl", 240, true} // or all, in order novel.Read = true // the dot reads and changes fields fmt.Println(novel) fmt.Printf("%+v\n", tale) // %+v also shows the field names // Assigning a struct copies it. gift := tale gift.Title = "Matilda (gift)" fmt.Println(tale.Title, "|", gift.Title) // A slice of structs: a small bookshelf. shelf := []Book{novel, tale, {Title: "Dracula", Author: "Bram Stoker", Pages: 418}} total := 0 for i := 0; i < len(shelf); i++ { fmt.Printf("%-8s %-12s %4d %v\n", shelf[i].Title, shelf[i].Author, shelf[i].Pages, shelf[i].Read) total += shelf[i].Pages } fmt.Println("Total pages:", total)}Output · go run main.go
{Emma Jane Austen 474 true}
{Title:Matilda Author:Roald Dahl Pages:240 Read:true}
Matilda | Matilda (gift)
Emma Jane Austen 474 true
Matilda Roald Dahl 240 true
Dracula Bram Stoker 418 false
Total pages: 1132Key points
type Name struct { fields }defines a new type.T{Field: value}lets you skip fields;T{v1, v2}needs them all.variable.Fieldreads or changes a field.%+vprints a struct with its field names.- Assigning a struct makes a copy.
Exercise
Add a Year int field to Book, give each book a year and print only the ones with more than 400 pages, together with their year.