Go Structs, Methods, and Interfaces
Introduction
Go doesn't have classes. Instead, you group data in structs, attach behavior with methods, and describe what a type can do with interfaces. This tutorial builds a few shapes to show how the three fit together.
Prerequisites
- Go installed
- Understanding of functions and basic types
Step-by-Step Guide
Step 1: Define a struct and a method
A struct groups related fields. A method is a function with a receiver, written between func and the method name.
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}Step 2: Use a pointer receiver to modify a value
A method with a value receiver works on a copy. Use a pointer receiver (*Rectangle) when the method needs to change the original.
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
rect := Rectangle{Width: 3, Height: 4}
rect.Scale(2)
fmt.Println(rect.Area()) // 48Step 3: Describe behavior with an interface
An interface lists method signatures. Any type with those methods satisfies it automatically, without declaring that it does so.
import "math"
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}Step 4: Write code against the interface
A function that accepts a Shape works with any type that has an Area method.
func printArea(s Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
}
printArea(Rectangle{Width: 3, Height: 4}) // Area: 12.00
printArea(Circle{Radius: 2}) // Area: 12.57FAQs
- Does Go support inheritance?
- Not in the class-based sense. Go favors composition: you embed one struct in another and use interfaces to share behavior.
- How does a type implement an interface in Go?
- Implicitly. If a type has all the methods an interface requires, it satisfies the interface; there is no implements keyword.
Summary
Structs hold data, methods add behavior, and interfaces let functions work with any type that has the right methods. Use pointer receivers when a method must modify its receiver.
Comments
Log in or create a free account to join the discussion.