Go Structs & Methods Cheat Sheet
Explains defining Go structs, value versus pointer method receivers, struct embedding for composition, and how Go achieves reuse without inheritance.
2 PagesBeginnerApr 2, 2026
Structs
Declaring and initializing struct values.
go
type Point struct { X, Y int}p := Point{X: 3, Y: 4} // Named fieldsp2 := Point{5, 6} // Positional (must set all fields, in order)p3 := Point{} // Zero value: X=0, Y=0fmt.Println(p.X, p.Y)
Methods with Value & Pointer Receivers
Choosing between copying and mutating the receiver.
go
func (p Point) Distance() float64 { // Value receiver: operates on a copy return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))}func (p *Point) Scale(factor int) { // Pointer receiver: mutates the original p.X *= factor p.Y *= factor}p := Point{X: 3, Y: 4}fmt.Println(p.Distance()) // 5p.Scale(2) // Go automatically takes &p for pointer receiversfmt.Println(p) // {6 8}
Embedding (Composition)
Reusing fields and methods without classical inheritance.
go
type Base struct { ID int}func (b Base) Describe() string { return fmt.Sprintf("ID=%d", b.ID)}type User struct { Base // Embedded struct -- promotes Base's fields and methods Name string}u := User{Base: Base{ID: 1}, Name: "Alice"}fmt.Println(u.ID) // Promoted field, accessible directlyfmt.Println(u.Describe()) // Promoted method
Concepts
Key rules for structs and their method sets.
- Zero value- A struct's fields default to their type's zero value if not explicitly initialized
- Value vs pointer receiver- Pointer receivers avoid copying and allow mutation; use them consistently across a type's methods
- Struct embedding- Go's mechanism for composition; the embedded type's fields/methods are "promoted" to the outer type
- No inheritance- Go has no classical inheritance -- embedding plus interfaces achieve similar reuse
- Struct comparison- Structs are comparable with == if all of their fields are comparable
- Struct tags- `json:"name"` metadata used by encoding/json and other reflection-based libraries
- Anonymous structs- x := struct{ A int }{A: 1} defines a one-off, unnamed struct type
Pro Tip
Be consistent with receiver types across a struct's method set -- mixing value and pointer receivers can cause a type to unexpectedly fail to satisfy an interface, since only *T gets the pointer-receiver methods.
Was this cheat sheet helpful?
Explore Topics
#GoStructsMethods#GoStructsMethodsCheatSheet#Programming#Beginner#Structs#Methods#Value#Pointer#OOP#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance