Structs Cheatsheet
Basic Definition
type User struct {
Name string
Age int
}
Instantiation
u := User{Name: "Bob", Age: 30}
u.Name = "Alice" // Dot operator
Advanced Types
- Nested:
type A struct { b B } -> a.b.field
- Embedded:
type A struct { B } -> a.field (Field promotion)
- Anonymous:
val := struct{ x int }{ x: 10 }
- Empty:
struct{}{} (Zero bytes)
Methods
func (u User) Greet() string {
return "Hello " + u.Name
}
Memory Optimization
- Fields are contiguous.
- Ordering from largest to smallest reduces padding.
- Use
reflect.TypeOf(s{}).Size() to check memory usage.
Key Concepts
- Structs are the primary way to group related data.
- Dot operator
. is used for all field and method access.
- Embedded structs allow for a form of composition/inheritance.