Structs are custom data types in Go that allow you to group together variables of different types under a single type. They are similar to classes in object-oriented programming languages but are simpler and do not provide inheritance, methods, or constructors.
Defining Structs
To define a struct in Go, use the type keyword followed by the struct name and keyword struct. Structs are defined at the package level, allowing them to be used across multiple functions within the same package.
package main
import "fmt"
type Person struct {
Name string
Age int
}In this example, a struct named Person is defined with two fields: Name of type string, and Age of type int.
Basic Initialization
After defining a struct, initializing it can be done using field names within a struct literal.
func main() {
// Initializing a Person struct
bob := Person{
Name: "Bob",
Age: 25,
}
fmt.Println(bob)
}This initializes a Person instance with the name "Bob" and age 25.
Intermediate Struct Initialization without Field Names
Go also supports initializing a struct without specifying field names. Fields are initialized in the order they are defined in the struct.
func main() {
// Initializing a Person struct without field names
alice := Person{"Alice", 30}
fmt.Println(alice)
}Note that using this method of initialization can make your code less readable, especially as the number of fields in the struct increases.
Pointers and Structs
Like any other data type, you can create a pointer to a struct using the & operator.
func main() {
// Using a pointer to intern a struct
p := &Person{Name: "Charlie", Age: 28}
fmt.Println(p)
}Pointers are especially useful when you want to modify the struct data without copying it and when structures are large, helping with efficient memory use.
Advanced Structs: Embedded Structs
Go supports embedded structs, allowing you to compose and reuse struct types.
type Address struct {
City string
State string
}
type Contact struct {
Person // Embedded struct
Email string
Address // Embedded struct
}
func main() {
john := Contact{
Person: Person{Name: "John", Age: 35},
Email: "[email protected]",
Address: Address{
City: "Citysville",
State: "Stateland",
},
}
fmt.Println(john)
}An embedded struct allows you to directly access fields of the embedded type. For example, you can access Name from john directly as john.Name.
Conclusion
Structs are a powerful way to create complex data types in Go through composition rather than inheritance. With this guide, you should be able to define, initialize, and manipulate structs in Go comfortably.