Skip to content
OBLAIDISH NEWS
Go struct embedding differs from class inheritance
TX_388095Engineering

Go struct embedding differs from class inheritance

Gabriel Anhaia's article on dev.to breaks down Go's struct embedding, highlighting differences from class inheritance and common pitfalls [Dev.to].

Gabriel Anhaia published a guide on Go struct embedding on dev.to, explaining how it differs from class inheritance [Dev.to]. The article demonstrates the canonical embedding syntax, where declaring a field of type Engine inside Car without a name promotes Engine's fields and methods onto Car [Dev.to]. However, the promoted method runs against the embedded type, so it cannot access any outer fields such as Car.Brand [Dev.to]. Anhaia also shows how embedding a pointer type (*Conn) automatically satisfies the Closer interface, allowing a Service value to be passed to a []Closer slice without explicit declaration [Dev.to]. This can cause a generic cleanup routine to close a live connection unintentionally. The guide covers name collisions, where embedding both Reader and Writer structs creates an ambiguous selector on Pipe, forcing developers to write a disambiguating wrapper method [Dev.to]. Anhaia lists scenarios where embedding is appropriate, such as exposing a full interface surface or building mix-in utilities like sync.Mutex [Dev.to]. In other cases, he recommends a named field to keep the outer type's API explicit [Dev.to]. Unintended interface implementation can occur when embedding a pointer that implements Close, making the outer type a Closer without a visible contract [Dev.to]. Method-name collisions increase maintenance cost, as the compiler only reports an error at the call site, forcing developers to add wrapper methods later [Dev.to]. Developers from class-based languages often expect a promoted method to see the outer struct's fields, but the method's receiver is the embedded type, causing logical errors [Dev.to].

operator_channel
[ comments_offline · provider_not_configured ]
transmission_log

Subscribe to the broadcast.

Daily digest of the day's most important tech news. No fluff. Engineering signal only.

// delivered via substack · double-opt-in confirmation