Master Go’s Object‑Oriented Patterns: Structs, Methods, and Interfaces Explained
This article walks through Go’s approach to object‑oriented design using a pet‑clinic example, covering struct definitions, pointer vs. value receivers, interface contracts, and a practical payment‑gateway demo, while illustrating memory behavior and the language’s duck‑typing philosophy.
Structs: Real‑World Data Blueprint
In Go, structs serve as the core way to organize data, similar to classes in other languages. The example defines a Pet struct with fields Name, Age, and Breed, and shows three ways to instantiate it:
type Pet struct {
Name string
Age int
Breed string // 品种
}
// Zero‑value initialization
var p1 Pet // {"", 0, ""}
// Literal initialization
p2 := Pet{"小白", 3, "泰迪"}
// Pointer initialization (recommended)
p3 := &Pet{"小黑", 2, "金毛"}Why use a pointer? It avoids copying large objects (performance) and allows methods to modify the original instance.
Avoids large object copies
Method changes affect the original data
Methods: Giving Types Behaviour
A method is a function with a receiver. The receiver type determines whether the method can modify the original data.
// Value receiver – works on a copy
func (p Pet) CelebrateBirthday() {
p.Age++ // modifies copy only
}
// Pointer receiver – works on the original
func (p *Pet) RealBirthday() {
p.Age++ // modifies original
}
func main() {
dog := Pet{"旺财", 2, "柴犬"}
dog.CelebrateBirthday()
fmt.Println(dog.Age) // still 2
dog2 := &Pet{"旺财2", 2, "柴犬"}
dog2.RealBirthday()
fmt.Println(dog2.Age) // becomes 3
}Memory diagram : a value receiver copies the whole struct to new memory, while a pointer receiver passes the address, resulting in zero‑copy.
Interfaces: Go’s Soulful Design
Interfaces define a contract of behaviour without caring about the implementer. Any type that provides the required method set satisfies the interface implicitly.
// Define a "Vocal" interface
type Vocal interface {
Speak() string
}
// Cat implements Vocal
type Cat struct { Name string }
func (c Cat) Speak() string { return "喵~" }
// Dog implements Vocal
type Dog struct { Name string }
func (d Dog) Speak() string { return "汪!" }
// Generic function using the interface
func MakeSound(v Vocal) {
fmt.Println(v.Speak())
}
func main() {
MakeSound(Cat{"咪咪"}) // 喵~
MakeSound(Dog{"旺财"}) // 汪!
}Key interface concepts :
Implicit implementation : no implements keyword; matching method set is enough.
Small interface principle : e.g., io.Reader has a single Read() method; composition beats inheritance.
Empty interface interface{}: can hold values of any type, similar to Java’s Object.
Practical Example: Decoupling Business Logic with Interfaces
The demo shows a payment processing scenario where the business code depends only on a Payment interface, allowing easy swapping of concrete implementations.
// Payment interface
type Payment interface {
Pay(amount float64) error
}
// WeChat Pay implementation
type WechatPay struct {}
func (w WechatPay) Pay(amount float64) error {
fmt.Printf("微信支付 %.2f 元
", amount)
return nil
}
// Alipay implementation
type Alipay struct {}
func (a Alipay) Pay(amount float64) error {
fmt.Printf("支付宝支付 %.2f 元
", amount)
return nil
}
// Business logic that is agnostic of the payment method
func Checkout(p Payment, amount float64) {
if err := p.Pay(amount); err != nil {
log.Println("支付失败:", err)
}
}
// Switching payment methods requires only one line change
Checkout(WechatPay{}, 99.9) // 微信支付
Checkout(Alipay{}, 99.9) // 支付宝支付The article demonstrates how Go’s struct‑method‑interface combination enables clean, decoupled designs that resemble object‑oriented patterns without explicit inheritance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Wrench
Focuses on code debugging, performance optimization, and real-world engineering, sharing efficient development tips and pitfall guides. We break down technical challenges in a down-to-earth style, helping you craft handy tools so every line of code becomes a problem‑solving weapon. 🔧💻
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
