Go — Structs
Basic struct
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p1 := Person{Name: "Alice", Age: 30}
p2 := Person{"Bob", 25}
fmt.Println(p1.Name)
fmt.Println(p2)
}
Nested structs
type Address struct {
Street string
City string
Zip string
}
type Person struct {
Name string
Age int
Address Address
}
func main() {
p := Person{
Name: "Alice",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "NYC",
Zip: "10001",
},
}
fmt.Println(p.Address.City)
}
Struct methods
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
func main() {
r := Rectangle{Width: 5, Height: 3}
fmt.Println("Area:", r.Area())
r.Scale(2)
fmt.Println("Scaled area:", r.Area())
}
Anonymous structs
point := struct {
X, Y int
}{X: 1, Y: 2}
fmt.Println(point)
Struct tags
type User struct {
Name string `json:"name" db:"user_name"`
Email string `json:"email" db:"email"`
Age int `json:"age,omitempty" db:"age"`
}
Best practices
- Use structs over maps for fixed data shapes
- Use pointer receivers for methods that modify state
- Use value receivers for read-only methods
- Keep structs small and focused
Mini Practice
Write Go code that:
- Creates a
Personstruct with a method - Uses nested structs
- Creates an anonymous struct
- Demonstrates pointer vs value receivers
Up Next
In the next lesson, you'll learn about Pointers — memory addresses in Go.
Related Topics
Frequently Asked Questions about Structs
What is Structs in Go?
Structs is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Structs?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Structs.
Why is Structs important in Go?
Structs is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.