Structs & Custom Methods
Go does not have classes or objects. Instead, custom data structures are defined using structs, and methods are bound to structs using receiver functions.
1 Value vs. Pointer Receivers
Methods are functions declared with a **Receiver** argument, which binds the function to a specific type. There are two types of receivers:
- Value Receiver: Passes a copy of the struct. Modifying struct fields inside the method does not affect the original object.
- Pointer Receiver (`*Type`): Passes a pointer to the struct. Modifying fields inside the method changes the original object directly. Used to avoid copying large structures in memory.
2 Structs & Methods Code
Let's run a program declaring structures and binding value/pointer receiver methods:
Go — Structs & Receivers
▶ Run Code
package main
import "fmt"
struct Student {
Name string
Grade float64
}
// Value Receiver (cannot modify original struct)
func (s Student) printDetails() {
fmt.Printf("Student: %s, Grade: %.2f\n", s.Name, s.Grade)
}
// Pointer Receiver (modifies original struct)
func (s *Student) updateGrade(newGrade float64) {
s.Grade = newGrade
}
func main() {
s := Student{Name: "Alice", Grade: 3.8}
s.printDetails()
s.updateGrade(3.95) // Automatically passes pointer reference
s.printDetails() // Displays updated grade
}
3 Code Challenge
Challenge: Write a struct called `Car` with a property `Speed` (int). Create a pointer receiver method called `Accelerate(amount int)` that increases the speed. Instantiate a car, accelerate it by `30`, and print the updated speed.