Types, Structs & Methods
Definition
Object
- In plain English
- An object is a bundle of data plus the actions that work on that data.
- Think of it like
- It is like a TV remote that holds the current channel and has buttons to change it.
Struct
- In plain English
- A struct is a Go type that groups related fields under one name.
- Think of it like
- It is like a form with a fixed set of labelled boxes.
Method
- In plain English
- A method is a function attached to a type and called on a value of that type.
- Think of it like
- It is like a button on one specific appliance.
Why it exists
You store roomName, targetTemp1, targetTemp2 and mode in separate variables. Soon you cannot tell which target belongs to which room.
Class
- In plain English
- A class is the blueprint that languages like Java use to define objects, and Go uses structs plus methods instead.
- Think of it like
- It is like a cookie cutter that stamps out cookies of the same shape.
Group one room’s temperatures in a Thermostat. Give its temperature rules a home beside that data. In Go, you do this without declaring a class.
How it works
Receiver
- In plain English
- A receiver is the value a method is called on, written in parentheses before the method name.
- Think of it like
- It is like the name on a task card, saying who should do the job.
Pointer receiver
- In plain English
- A pointer receiver lets a method change the original value instead of a copy.
- Think of it like
- It is like editing the shared document instead of a photocopy.
package main
import "fmt"
type Thermostat struct {
Room string
TargetC, CurrentC float64
}
func (t *Thermostat) SetTarget(c float64) error {
if c < 5 || c > 30 {
return fmt.Errorf("target must be 5–30 C")
}
t.TargetC = c
return nil
}
func (t Thermostat) NeedsHeat() bool { return t.CurrentC < t.TargetC }
func main() {
t := Thermostat{Room: "study", CurrentC: 18}
if err := t.SetTarget(21); err != nil {
panic(err)
}
fmt.Println(t.NeedsHeat())
}
Thermostat groups Room, TargetC and CurrentC fields. Its SetTarget method accepts a temperature and returns an error; NeedsHeat returns true or false.
| Receiver | Copies what? | Changes original fields? | Use when |
|---|---|---|---|
| t Thermostat | The struct value | No, not by assigning its fields | Reading a small value |
| t *Thermostat | A pointer to the struct | Yes | Updating state or avoiding a large copy |
type Counter struct{ n int }
func (c Counter) Inc() { c.n++ }
func broken() { c := Counter{}; c.Inc(); c.Inc(); println(c.n) }
// broken prints 0: each Inc changes its receiver copy.
Examples
Eco and comfort modes
You add an eco or comfort mode to the thermostat without scattering more room variables.
type Thermostat struct {
Room string
TargetC, CurrentC float64
Mode string // "eco" or "comfort"
}
Keep SetTarget, NeedsHeat and Mode on Thermostat because they describe one room. Sending notifications is a separate job.
The insight
Data and the rules about it live together.
A dock with a capacity
A dock must reject a returned bike when every space is occupied.
package main
import "fmt"
type Dock struct {
ID string
Capacity int
bikes []string
}
func (d *Dock) Dock(bikeID string) error {
if len(d.bikes) >= d.Capacity {
return fmt.Errorf("dock full")
}
d.bikes = append(d.bikes, bikeID)
return nil
}
func (d *Dock) Undock() (string, error) {
if len(d.bikes) == 0 {
return "", fmt.Errorf("dock empty")
}
id := d.bikes[0]
d.bikes = d.bikes[1:]
return id, nil
}
func main() {
d := Dock{ID: "D1", Capacity: 1}
fmt.Println(d.Dock("B7"))
fmt.Println(d.Undock())
}
Both methods change the stored bike list, so both use pointer receivers.
The insight
Methods guard the struct’s own rules.
A review changes the interval
A correct answer doubles the review interval. A wrong answer resets it to one day.
package main
import "fmt"
type Card struct {
Front, Back string
IntervalDays int
}
func (c *Card) Review(correct bool) {
if correct {
c.IntervalDays *= 2
} else {
c.IntervalDays = 1
}
}
func main() {
c := Card{Front: "Go receiver?", Back: "Value or pointer", IntervalDays: 1}
c.Review(true)
fmt.Println(c.IntervalDays)
c.Review(false)
fmt.Println(c.IntervalDays)
}
Review owns the interval rule. The screen can display the result without implementing that rule again.
The insight
Behaviour that belongs to the data becomes a method on it.
Trade-offs
Pros
- Related data and behaviour stay together.
- Focused types are readable and reusable.
Cons
- One struct risks collecting too many jobs.
- Receiver choices need care around shared data.
Use when
- Data has rules.
- Several functions operate on the same meaningful value.
Avoid when
- Data only passes through the program.
- A standalone function expresses the task more directly.
Quick check
Takeaways
- Structs group data; methods attach behaviour.
- Use pointer receivers to modify.
- Keep each type focused.