Description
A struct is a collection of fields. It is useful for grouping data together to form records. Go is object-oriented but uses structs and methods instead of classes.
Pros & Cons
✅ Pros
- Lightweight objects.
- Memory layout control.
❌ Cons
- No Inheritance: Go uses composition instead of inheritance.
When to Use
Defining object models.
Example
Defining and using structs.
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v)
}
Best Practices
Use capitalized field names (e.g., `X` vs `x`) to export them to other packages.
