Structs in Go
Structs in Go are user-defined types that group together fields. They are similar to classes in other languages but do not support inheritance. Structs are widely used in Go for organizing and managing data.
Defining a Struct
A struct is defined using the type
and struct
keywords. Structs can contain fields of different types.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println("Name:", p.Name)
fmt.Println("Age:", p.Age)
}
Methods on Structs
Methods are functions that operate on a specific type. They are defined with a receiver argument, which can be a value or a pointer.
package main
import "fmt"
type Person struct {
Name string
Age int
}
// Method with a value receiver
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}
// Method with a pointer receiver
func (p *Person) Birthday() {
p.Age++
}
func main() {
p := Person{Name: "Alice", Age: 25}
p.Greet()
p.Birthday()
fmt.Println("New Age:", p.Age)
}
Embedded Structs
Structs can be embedded within other structs to create more complex data structures. This is similar to inheritance in other languages.
package main
import "fmt"
type Address struct {
City string
State string
}
type Person struct {
Name string
Age int
Address Address
}
func main() {
p := Person{
Name: "Alice",
Age: 25,
Address: Address{
City: "New York",
State: "NY",
},
}
fmt.Println("Name:", p.Name)
fmt.Println("City:", p.Address.City)
}
Pointers to Structs
You can use pointers to structs to avoid copying large structs and to modify the original struct.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p *Person) UpdateName(newName string) {
p.Name = newName
}
func main() {
p := &Person{Name: "Alice", Age: 25}
p.UpdateName("Bob")
fmt.Println("Updated Name:", p.Name)
}
Anonymous Structs
Anonymous structs are structs that are defined without a name. They are useful for one-time use cases.
package main
import "fmt"
func main() {
p := struct {
Name string
Age int
}{
Name: "Alice",
Age: 25,
}
fmt.Println("Name:", p.Name)
fmt.Println("Age:", p.Age)
}
Struct Tags
Struct tags are used to attach metadata to struct fields. They are commonly used in JSON encoding/decoding.
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{Name: "Alice", Age: 25}
jsonData, _ := json.Marshal(p)
fmt.Println("JSON:", string(jsonData))
}
Practical Use Cases
Structs are widely used in Go for:
- Data Modeling: Representing real-world entities like users, products, etc.
- API Responses: Structuring JSON responses in web applications.
- Configuration: Storing configuration settings in a structured way.