Ad space (banner)
๐ŸนGo Lessons
Lesson 16 / 68

Reusing Code with Struct Embedding

In this lesson you will learn to reuse code with struct embedding in Go, achieving something close to inheritance. This is for anyone searching for "Go struct embedding how to use".

Go has no "inheritance", but embedding one struct inside another lets you reuse its fields and methods directly.

The sample code embeds the Animal struct inside the Dog struct, so dog.Speak() calls the method that Animal owns. The fields and methods of an embedded struct are reachable as though they were the outer struct's own.

A common stumbling block for beginners is the difference between embedding and inheritance. It helps to understand the Go philosophy at work: rather than building deep inheritance hierarchies, you compose just the functionality you need.

In real-world development embedding is widely used whenever you want to gather functionality shared by several structs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)