Struct Basics
Introduction to Structs in Go
In Go programming, structs are fundamental data structures that allow you to create custom types by combining different fields. They provide a way to group related data together, making code more organized and expressive.
Defining a Struct
A basic struct definition looks like this:
type Person struct {
Name string
Age int
Address string
}
Creating Struct Instances
You can create struct instances in multiple ways:
// Method 1: Using field names
person1 := Person{
Name: "Alice",
Age: 30,
Address: "New York",
}
// Method 2: Positional initialization
person2 := Person{"Bob", 25, "San Francisco"}
// Method 3: Creating an empty struct and then assigning values
var person3 Person
person3.Name = "Charlie"
person3.Age = 35
Struct Methods
Structs can have associated methods:
func (p Person) Introduce() string {
return fmt.Sprintf("Hi, I'm %s, %d years old", p.Name, p.Age)
}
Struct Characteristics
Feature |
Description |
Zero Value |
Structs have a zero value where all fields are set to their zero values |
Immutability |
Structs are value types in Go |
Memory Efficiency |
Compact memory representation |
Struct Memory Visualization
graph TD
A[Struct Memory Layout] --> B[Field 1]
A --> C[Field 2]
A --> D[Field 3]
Best Practices
- Keep structs focused and cohesive
- Use meaningful field names
- Consider using constructor functions for complex initializations
By understanding these struct basics, you'll have a solid foundation for more advanced Go programming techniques. LabEx recommends practicing these concepts to gain proficiency.