Go Structs
A struct is a value that groups named fields of data together. Each field has a name and a type.
A struct type and a value
The Person type groups a name and an age. The dot reads one field at a time.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Hana", Age: 27}
fmt.Println(p.Name)
fmt.Println(p.Age)
}Write a field after creation
The dot also writes a field. The age changes from 22 to 23 after the assignment.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Ana", Age: 22}
p.Age = 23
fmt.Println(p.Name, p.Age)
}Print a struct with %v and %+v
The %v verb prints the values in field order. The %+v verb adds the field names to the same line shape.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Hana", Age: 27}
fmt.Printf("%v\n", p)
fmt.Printf("%+v\n", p)
}A struct inside a struct
The Home field of Employee holds an Address value. Two dots in a row reach the city field inside it.
package main
import "fmt"
type Address struct {
City string
Zip int
}
type Employee struct {
Name string
Home Address
}
func main() {
e := Employee{Name: "Hana", Home: Address{City: "Seattle", Zip: 98101}}
fmt.Println(e.Home.City)
fmt.Println(e.Home.Zip)
}Example
package main
import "fmt"
type Book struct {
Title string
Author string
Pages int
}
func main() {
b := Book{Title: "Go Basics", Author: "Ana Ruiz", Pages: 180}
fmt.Println("Title:", b.Title)
fmt.Println("Pages:", b.Pages)
}Key points
- Use the type keyword to define a struct and its fields.
- A field is one named piece of data inside a struct.
- A struct literal lists a value for each field by field name.
- Use a dot to read or write a field of a struct value.
- The %v verb prints the field values in field order.
- The %+v verb prints the field names beside the values.
In this example, the Book struct groups a title, an author, and a page count. Main builds one Book value with all three fields filled in. The print lines read the title and the page count through the dot.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
How does code read the Age field of a Person value named p?