Structs in Go
| Define a struct | |
| Composite literals | |
| Access fields | |
| Compare and copy |
Define a struct
A struct groups related fields of different types under one named type. Define it once with the type keyword, then every variable of that type carries the same set of fields.
package main
import "fmt"
type Point struct {
X int
Y int
}
func main() {
var p Point
fmt.Println(p)
}
go run main.go
{0 0}
A fresh struct holds the zero value in every field, so printing it shows {0 0} here. Field names start with a capital letter when other packages must see them.
Composite literals
Composite literals build a value and set fields in one expression. Name the fields for clarity, or list values in field order for very short throwaway values.
package main
import "fmt"
type Point struct {
X int
Y int
}
func main() {
p1 := Point{X: 1, Y: 2}
p2 := Point{3, 4}
fmt.Println(p1, p2)
}
{1 2} {3 4}
Field names protect against reordering: adding a field in the middle breaks positional literals but leaves named ones working. Prefer named fields in real code.
Access fields
Reach a field with a dot: read it into expressions or assign a fresh value through the same path. Nested structs chain dots, one per level.
package main
import "fmt"
type User struct {
Name string
Age int
}
func main() {
u := User{Name: "Ada", Age: 36}
u.Age = 37
fmt.Println(u.Name, u.Age)
}
Ada 37
The dot works through pointers too: Go follows the pointer automatically, so u.Age reads the same whether u is a struct or a pointer to one.
Compare and copy
Structs without slice or map fields compare with == and copy field by field on assignment. That value behavior makes small records safe to duplicate and test for equality.
package main
import "fmt"
type Point struct {
X int
Y int
}
func main() {
a := Point{X: 1, Y: 2}
b := a
fmt.Println(a == b)
b.X = 9
fmt.Println(a, b)
}
true
{1 2} {9 2}
Assignment copies the whole value, so later changes to b leave a untouched. Use pointers from the previous lesson when many copies would cost too much or shared state is the goal.
Next: Methods
Article author: Arthur Isaev