Structs
Define a struct
A struct is a typed collection of fields.
type User struct {
Name string
Age int
}
func main() {
u := User{Name: "Ada", Age: 28}
fmt.Println(u.Name)
}
Update fields
Use dot notation to read and write fields on a value.
u.Age = 29
fmt.Println(u)
Pointers to structs
Methods and helpers often take *User so they can modify the original.
func birthday(u *User) {
u.Age++
}
birthday(&u)
fmt.Println(u.Age)
Struct tips
- Capitalize field names to export them from a package
- Use keyed literals (
Name:) for clarity - Zero value structs have zeroed fields
- Embed structs later for composition
Comments
One comment per signed-in account. Comments are saved with this page’s URL.