Introduction
Nested structs help organize related information inside other information, like putting a smaller box inside a bigger box.
type Inner struct {
Field1 string
Field2 int
}
type Outer struct {
InnerField Inner
}type Address struct {
City string
ZipCode int
}
type Person struct {
Name string
Age int
Home Address
}type Engine struct {
Horsepower int
}
type Car struct {
Brand string
Engine Engine
}package main import "fmt" type Address struct { City string ZipCode int } type Person struct { Name string Age int Home Address } func main() { p := Person{ Name: "Alice", Age: 30, Home: Address{ City: "Wonderland", ZipCode: 12345, }, } fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age) fmt.Println("City:", p.Home.City) fmt.Println("Zip Code:", p.Home.ZipCode) }
nested structs in Go?City inside a nested struct Address within struct Person?package main
import "fmt"
type Address struct {
City string
Zip int
}
type Person struct {
Name string
Address Address
}
func main() {
p := Person{Name: "Anna", Address: Address{City: "Paris", Zip: 75000}}
fmt.Println(p.Address.City)
}p.Address.City, which is "Paris".package main
import "fmt"
type Engine struct {
Power int
}
type Car struct {
Model string
Engine Engine
}
func main() {
c := Car{Model: "Sedan"}
fmt.Println(c.Engine.Power)
}FullAddress that returns a formatted string combining Street, City, and Zip from nested structs?
type Location struct {
Street string
City string
}
type Address struct {
Location Location
Zip int
}Pass the test and this pattern moves unknown