A struct in Go is a composite data type that groups together variables under one name, making it easier to manage and manipulate them. These variables within the struct are called fields and can have different data types. Structs are useful for creating custom data types, modeling real-world entities, and representing more complex data structures.
Here’s a simple example of a struct:
package main
import "fmt"
// Define a struct named 'Person'
type Person struct {
Name string
Age int
City string
}
func main() {
// Create an instance of the 'Person' struct
person1 := Person{"Alice", 25, "New York"}
// Access and modify the fields of the struct
fmt.Println(person1.Name) // Output: Alice
person1.Age = 26
fmt.Println(person1.Age) // Output: 26
// Another way to create an instance of the 'Person' struct
person2 := Person{
Name: "Bob",
Age: 30,
City: "London",
}
fmt.Println(person2) // Output: {Bob 30 London}
}
In this example, we defined a ‘Person‘ struct with three fields: ‘Name‘, ‘Age‘, and ‘City‘. We then created instances of the struct ‘person1‘ and ‘person2‘ and accessed and modified their fields.
Here’s the same struct:
type Person struct {
Name string
Age int
City string
}func main() {
person1 := Person{"Alice", 25, "New York"}
fmt.Println(person1.Name) // Output: Alice
person1.Age = 26
fmt.Println(person1.Age) // Output: 26
person2 := Person{
Name: "Bob",
Age: 30,
City: "London",
}
fmt.Println(person2) // Output: {Bob 30 London}
}