Structs
Structs in Go
Go uses structs to group related data — they are the primary way to create custom types.
Struct definition
type Point struct {
X, Y float64
}Struct literals Create struct values using named fields (preferred) or positional fields:
p := Point{X: 1.0, Y: 2.0}Anonymous (embedded) fields Embed a type without naming it. Its fields and methods are promoted to the embedding struct:
type Animal struct { Name string }
type Dog struct {
Animal // embedded
Breed string
}
d := Dog{Animal: Animal{"Rex"}, Breed: "Lab"}
fmt.Println(d.Name) // promotedNested structs A struct field can be another struct type — used for composition.
Key points:
- Structs are value types in Go — assignment copies all fields.
- Use
&StructType{}to get a pointer to a struct. - Zero value of a struct has all fields at their zero values.
- Exported fields start with an uppercase letter; unexported with lowercase.
Code Examples
package main
import (
"fmt"
"math"
)
type Point struct {
X, Y float64
}
func distance(a, b Point) float64 {
dx := a.X - b.X
dy := a.Y - b.Y
return math.Sqrt(dx*dx + dy*dy)
}
type Rectangle struct {
TopLeft Point
BottomRight Point
}
func (r Rectangle) Area() float64 {
w := math.Abs(r.BottomRight.X - r.TopLeft.X)
h := math.Abs(r.BottomRight.Y - r.TopLeft.Y)
return w * h
}
func main() {
p1 := Point{0, 0}
p2 := Point{X: 3, Y: 4}
fmt.Printf("Distance: %.1f\n", distance(p1, p2))
rect := Rectangle{TopLeft: Point{0, 4}, BottomRight: Point{3, 0}}
fmt.Printf("Area: %.1f\n", rect.Area())
}Structs compose naturally. Rectangle nests Point structs. Methods can be defined on struct types (shown in next lesson).
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Describe() string {
return "Animal: " + a.Name
}
type Dog struct {
Animal
Breed string
}
func main() {
d := Dog{
Animal: Animal{Name: "Rex"},
Breed: "Labrador",
}
fmt.Println(d.Name) // promoted field
fmt.Println(d.Describe()) // promoted method
fmt.Println(d.Breed)
}Embedded types promote their fields and methods. This is Go's preferred composition mechanism instead of classical inheritance.
Quick Quiz
1. What happens when you assign a struct to a new variable in Go?
2. What does embedding a type in a struct do?
Was this lesson helpful?