今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Go's Type System — Structs, Interfaces, and Life Without Inheritance

mihir mohapatra 2026年06月19日 14:53 5 次阅读 来源:Dev.to

Go's Type System — Structs, Interfaces, and Life Without Inheritance In part 1 of this series I talked about why I'm picking up Go after six years of Java and Kotlin, plus a recent deep dive into Rust. This time I want to get into the part that actually changed how I think about designing code: Go has no class inheritance at all. Coming from the JVM world, that sentence sounded alarming the first time I read it. No extends . No abstract classes. No polymorphism through a class hierarchy. And yet Go backends at companies running serious scale seem to do just fine without it. After a few weeks living inside Go's type system, I get why. Structs: Data, Nothing More A Go struct is just a typed bag of fields. No constructors, no access modifiers in the Java sense, no inheritance: type Order struct { ID string Customer string Amount float64 Status string } func NewOrder ( id , customer string , amount float64 ) Order { return Order { ID : id , Customer : customer , Amount : amount , Status : "pending" , } } That NewOrder function is doing the job a constructor would do in Java — it's just a plain function by convention, not a language feature. Nothing stops you from building an Order{} directly with zero values either, which takes some adjusting to if you're used to constructors enforcing invariants. Methods attach to structs separately, outside the type definition: func ( o Order ) Total () float64 { return o . Amount } func ( o * Order ) MarkPaid () { o . Status = "paid" } That (o Order) vs (o *Order) distinction is the receiver type, and it trips up a lot of newcomers. A value receiver gets a copy of the struct; a pointer receiver can mutate the original. MarkPaid has to use a pointer receiver, or the status change would vanish the moment the method returns. No Inheritance, So What Replaces It? This is the part that took the most rewiring. In Java, if PremiumOrder needed everything Order had plus more, you'd write class PremiumOrder extends Order . Go simply doesn't hav

本文内容来源于互联网,版权归原作者所有
查看原文