Structs
Define and use structures in Go
#structs #types #objects #methods
Structs
Structs are typed collections of fields.
Defining Structs
type Person struct {
Name string
Age int
Email string
}
// Creating instances
p1 := Person{
Name: "Alice",
Age: 30,
Email: "alice@example.com",
}
p2 := Person{"Bob", 25, "bob@example.com"}
// Zero value
var p3 Person // All fields are zero values
Methods
type Rectangle struct {
Width, Height float64
}
// Method with value receiver
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Method with pointer receiver
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
// Usage
rect := Rectangle{Width: 10, Height: 5}
fmt.Println(rect.Area()) // 50
rect.Scale(2)
fmt.Println(rect.Area()) // 200
Embedded Structs
type Address struct {
City, State string
}
type User struct {
Name string
Address // Embedded struct
}
user := User{
Name: "Alice",
Address: Address{
City: "New York",
State: "NY",
},
}
// Access embedded fields
fmt.Println(user.City) // New York
Discover another handy tool from EditPDF.pro