Struct Basics
What is a Struct in Golang?
In Golang, a struct is a user-defined type that allows you to combine different data types into a single logical unit. It's similar to classes in other programming languages but without inheritance. Structs provide a way to create complex data structures that can represent real-world entities with multiple attributes.
Defining a Struct
Here's a basic example of defining a struct in Golang:
type Person struct {
Name string
Age int
Email string
}
Creating Struct Instances
You can create struct instances in multiple ways:
// Method 1: Using field names
person1 := Person{
Name: "John Doe",
Age: 30,
Email: "[email protected]",
}
// Method 2: Positional initialization
person2 := Person{"Jane Smith", 25, "[email protected]"}
// Method 3: Creating an empty struct and then assigning values
var person3 Person
person3.Name = "Alice"
person3.Age = 35
person3.Email = "[email protected]"
Struct Methods
Golang allows you to define methods on structs, which are functions associated with a specific type:
func (p Person) Introduce() string {
return fmt.Sprintf("Hi, I'm %s, %d years old", p.Name, p.Age)
}
Struct tags provide metadata about struct fields, which can be used for various purposes like JSON serialization:
type User struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"min=8"`
}
Struct Composition
Golang supports struct composition, which is similar to inheritance:
type Employee struct {
Person // Embedded struct
Company string
Salary float64
}
graph TD
A[Struct Memory Allocation] --> B[Contiguous Memory]
A --> C[Efficient Storage]
A --> D[Fast Access]
Structs in Golang are designed to be memory-efficient and provide fast access to their fields.
Key Characteristics
Characteristic |
Description |
Memory Layout |
Contiguous memory allocation |
Type Safety |
Strong type checking |
Flexibility |
Can contain multiple data types |
Performance |
Efficient memory usage |
By understanding these struct basics, you'll be well-prepared to use structs effectively in your Golang projects with LabEx.