Go Structs:
A struct in Go is a composite data type that groups together variables under a single name. These variables are called fields. Structs are commonly used to create custom data types.
Defining and Using Structs
Here's how to define and use a basic struct in Go:
go
package main
import "fmt"
// Define a struct type
type Person struct {
Name string
Age int
}
func main() {
// Create an instance of Person
var p1 Person
p1.Name = "Alice"
p1.Age = 30
fmt.Println("Name:", p1.Name)
fmt.Println("Age:", p1.Age)
}Struct Literal
You can also use a struct literal to initialize a struct directly:
go
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p2 := Person{Name: "Bob", Age: 25}
fmt.Println(p2)
}Pointer to Struct
Accessing struct fields via pointer is also straightforward using dot notation:
go
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := &Person{Name: "Charlie", Age: 35}
fmt.Println(p.Name)
fmt.Println(p.Age)
}Structs with Functions
You can associate methods with struct types in Go:
go
package main
import "fmt"
type Person struct {
Name string
Age int
}
// Method with struct receiver
func (p Person) Greet() {
fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.Name, p.Age)
}
func main() {
p := Person{Name: "Daisy", Age: 28}
p.Greet()
}