Structs
Go has no classes. Structs group related data.
type Student struct {
Name string
Marks []int
}
s := Student{Name: "Asha", Marks: []int{80, 90}}
fmt.Println(s.Name, s.Marks[0])Methods
A method is a function attached to a type.
func (s Student) Average() float64 {
total := 0
for _, m := range s.Marks {
total += m
}
return float64(total) / float64(len(s.Marks))
}
fmt.Println(s.Average())Pointers and pointer receivers
Use a pointer receiver when the method must change the struct.
func (s *Student) AddMark(m int) {
s.Marks = append(s.Marks, m)
}
s.AddMark(95)&x gets the address of x, and *p reads the value at pointer p.
Interfaces
An interface describes behaviour. Any type that has the methods automatically satisfies it. No implements keyword is needed.
type Shape interface {
Area() float64
}
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }
func printArea(s Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
}
func main() {
printArea(Rect{3, 4})
printArea(Circle{2})
}Embedding
type Person struct{ Name string }
type Teacher struct {
Person
Subject string
}
t := Teacher{Person{"Ravi"}, "Maths"}
fmt.Println(t.Name) // promoted fieldPractice
Create a BankAccount struct with Deposit and Withdraw methods that refuse to overdraw the account.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Define a struct and attach a method.
- Define an interface and make two types satisfy it.
- Use a pointer receiver and observe the difference.
Common mistakes
- Forgetting that interface satisfaction is implicit.
- Using value receivers when mutation is needed.
Quick check
How does a type implement an interface?
By having the required methods; no keyword needed.
Why use a pointer receiver?
To modify the value or avoid copying large structs.