Model records with structs
Model records with structs
A struct combines named fields into one value. Fields may have different types. Use a struct when a group of related values forms one meaningful record, such as a product with a name and quantity.
package main
import ( "fmt")
type Product struct { Name string Quantity int}
func main() { var p Product p.Name = "Pen" p.Quantity = 3 fmt.Println(p.Name, p.Quantity)}The declaration introduces a defined struct type. The selector p.Name accesses its field. A field declared with an uppercase initial is exported; lowercase names are available inside the declaring package but not from other packages.
Expected output:
Pen 3Use the zero value and a record slice
package main
import ( "fmt")
type Item struct { Name string Count int Active bool}
func main() { var empty Item fmt.Printf("%q %d %t\n", empty.Name, empty.Count, empty.Active) items := []Item{{Name: "Book", Count: 2}, {Name: "Pen", Count: 4}} total := 0 for _, it := range items { total += it.Count } fmt.Println(total)}A zero-valued struct has zero-valued fields. A slice of structs keeps the fields associated with each element. The range variable it is a copy of each struct; changing it does not change the slice element.
Expected output:
"" 0 false6Try it locally
Define a Book with Title string and Pages int. Create a Book, assign "Go" and 120, then print both fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 02: Model records with structs
Check the lesson objective before moving on.
What is the initial Count of var x struct{Count int}?
How do you access Name in a struct value p?