Struct Field 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 a class in object-oriented programming languages, but with some key differences.
Basic Struct Declaration
Here's a simple example of a struct declaration:
type Person struct {
name string
age int
height float64
}
Creating Struct Instances
You can create struct instances in multiple ways:
// Method 1: Named initialization
person1 := Person{
name: "Alice",
age: 30,
height: 1.75,
}
// Method 2: Positional initialization
person2 := Person{"Bob", 25, 1.80}
// Method 3: Empty struct and later assignment
var person3 Person
person3.name = "Charlie"
person3.age = 35
Struct Field Characteristics
Struct fields have several important characteristics:
Characteristic |
Description |
Type Flexibility |
Each field can have a different data type |
Default Values |
Unassigned fields get zero values |
Immutability |
Fields can be mutable or immutable |
Memory Representation
graph TD
A[Struct Memory Layout] --> B[Field 1]
A --> C[Field 2]
A --> D[Field 3]
Key Takeaways
- Structs are fundamental to organizing data in Golang
- They provide a way to group related data
- Fields can have different types and purposes
- Initialization can be done in multiple ways
Example with LabEx
When working on LabEx programming challenges, understanding struct basics is crucial for solving complex data modeling problems.