Struct Basics in Go
What is a Struct in Go?
A struct in Go is a user-defined type that allows you to combine different data types into a single logical unit. It's similar to a class in other programming languages but without inheritance. Structs are fundamental to organizing and structuring data in Go.
Defining a Struct
Here's a basic example of defining a struct:
type Person struct {
Name string
Age int
Email string
}
Creating Struct Instances
You can create struct instances in multiple ways:
// Method 1: Named initialization
person1 := Person{
Name: "Alice",
Age: 30,
Email: "[email protected]",
}
// Method 2: Positional initialization
person2 := Person{"Bob", 25, "[email protected]"}
// Method 3: Zero value initialization
var person3 Person
Accessing Struct Fields
Struct fields are accessed using dot notation:
fmt.Println(person1.Name) // Prints: Alice
person1.Age = 31 // Modifying field value
Struct Methods
Go allows you to define methods on structs:
func (p Person) Introduce() string {
return fmt.Sprintf("Hi, I'm %s, %d years old", p.Name, p.Age)
}
Struct Composition
Structs can be composed of other structs:
type Address struct {
Street string
City string
}
type Employee struct {
Person
Address
Position string
}
Struct Comparison
Structs can be compared if all their fields are comparable:
person4 := Person{Name: "Alice", Age: 30, Email: "[email protected]"}
isEqual := person1 == person4 // Compares all fields
graph TD
A[Struct Memory Allocation] --> B[Stack Allocation]
A --> C[Heap Allocation]
B --> D[Small, Fixed-Size Structs]
C --> E[Large or Pointer-Containing Structs]
Struct Best Practices
Practice |
Description |
Keep Structs Small |
Aim for focused, single-responsibility structs |
Use Composition |
Prefer composition over inheritance |
Immutability |
Consider making structs immutable when possible |
When to Use Structs
- Representing real-world entities
- Grouping related data
- Creating custom data structures
- Implementing object-like behavior
By understanding these struct basics, you'll be well-equipped to use structs effectively in your Go programming with LabEx.