Embedding instead of inheritance

Embedding is a field written as a type with no name. The outer struct then has the embedded type's fields and methods as if they were its own, which is the closest Go comes to inheritance and is deliberately less than it. The embedded value is a real field with the type name as its field name, so the outer type has not become the inner one: it has one. The structs lesson covered fields; this is what an unnamed field adds.

Promoted fields and methods

A field or method of the embedded type can be used through the outer value with no path: u.ID reaches u.Base.ID and u.Describe() calls the embedded method. Promotion is shallow, so a field of a field is not promoted twice, and the explicit path always works and is the way to say which value is meant.

package main import "fmt" type Base struct { ID int } func (b Base) Describe() string { return fmt.Sprintf("base %d", b.ID) } type User struct { Base Name string } func main() { u := User{Base: Base{ID: 1}, Name: "ada"} fmt.Println(u.ID, u.Name) fmt.Println(u.Describe()) fmt.Println(u.Base.ID) }

go run embed.go

1 ada
base 1
1

The two paths printed the same number, and the method ran with the embedded value as its receiver, not with the outer one. That is the first difference from inheritance: an overridden or inherited method knows only the embedded part, never the whole outer value, unless it is handed the outer value.

Shadowing and overriding

A field of the outer type with the same name hides the promoted one, and a method of the outer type with the same name replaces it for selectors on the outer value. The embedded method is still there under the explicit path. This is overriding by name resolution, not a virtual table: the compiler decides at the call site which method a selector means.

package main import "fmt" type Base struct { ID int } func (b Base) Describe() string { return fmt.Sprintf("base %d", b.ID) } func (b Base) Kind() string { return "base-kind" } type User struct { Base ID int Name string } func (u User) Describe() string { return "user " + u.Name } func main() { u := User{Base: Base{ID: 7}, ID: 9, Name: "ada"} fmt.Println(u.ID, u.Base.ID) fmt.Println(u.Describe(), "|", u.Kind()) fmt.Println(u.Base.Describe()) }

go run shadow.go

9 7
user ada | base-kind
base 7

u.ID is 9 and u.Base.ID is 7, and Kind was promoted while Describe was replaced. Because the choice is static, an embedded method cannot call the outer override: if Base.Describe called b.Kind(), it would get the base's Kind even when the outer value has its own.

Two embedded types, one name

When two embedded types provide the same name at the same depth, the selector is ambiguous and the compiler refuses it; there is no rule that prefers one. The fix is to name the path, c.A.Name(), or to give the outer type a method of its own that decides. This is the compiler forcing the ambiguity into the source, where a reader can see which one was meant.

package main type A struct{} func (A) Name() string { return "a" } type B struct{} func (B) Name() string { return "b" } type C struct { A B } func main() { var c C _ = c.Name() }

go build -o conflict conflict.go

# command-line-arguments
./conflict.go:18:8: ambiguous selector c.Name

The message names the selector and nothing else, because both candidates are equally close. An overload in the outer type resolves it by hiding both, which is often the right answer when the two embedded types are two roles of one object.

Embedding an interface

A struct can embed an interface, which delegates every method of that interface to the value in the field. That is how a decorator, a test double or a service with an injected logger is written without repeating method signatures: the embedded interface supplies them all, and the outer type adds its own behaviour on top.

package main import "fmt" type Logger interface { Log(string) } type console struct{} func (console) Log(s string) { fmt.Println("log:", s) } type Service struct { Logger Name string } func (s Service) Run() { s.Log("running " + s.Name) } func main() { s := Service{Logger: console{}, Name: "api"} s.Run() s.Logger.Log("direct call") }

go run iface.go

log: running api
log: direct call

The zero value of Service has a nil interface, so a call before the logger is set panics; a constructor that fills the field is the guard. This is composition with a named seam: the outer type does not inherit behaviour, it holds a value that provides it.

Exercises

  1. Embed a sync.Mutex in a cache struct and add Get and Set methods. Why is the mutex embedded rather than stored in a named field, and when is the named field better?
  2. Give two embedded types a method with the same name, then resolve the ambiguity with a method on the outer type that calls both. Which one does a caller reach without the new method?
  3. Wrap an io.Writer in a struct that counts bytes and then embeds the writer, so the wrapper satisfies io.Writer itself. What happens to the count when the caller calls Write twice?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an embedded field?

    Answer

    A field written as a type name with no field name

    The type name becomes the field name and its members are promoted to the outer type.

  2. What does the second line of this program print? package main import "fmt" type Base struct { ID int } func (b Base) Describe() string { return fmt.Sprintf("base %d", b.ID) } type User struct { Base Name string } func main() { u := User{Base: Base{ID: 1}, Name: "ada"} fmt.Println(u.ID, u.Name) fmt.Println(u.Describe()) fmt.Println(u.Base.ID) }

    Answer

    1 ada / base 1 / 1

    Describe runs on the embedded Base, whose ID is 1.

  3. Why is embedding not inheritance?

    Answer

    The outer value contains an inner value, and promoted methods see only the inner part

    There is no virtual dispatch: the method receiver is the embedded value, not the outer one.

  4. What does the first line of this program print? package main import "fmt" type Base struct { ID int } func (b Base) Describe() string { return fmt.Sprintf("base %d", b.ID) } func (b Base) Kind() string { return "base-kind" } type User struct { Base ID int Name string } func (u User) Describe() string { return "user " + u.Name } func main() { u := User{Base: Base{ID: 7}, ID: 9, Name: "ada"} fmt.Println(u.ID, u.Base.ID) fmt.Println(u.Describe(), "|", u.Kind()) fmt.Println(u.Base.Describe()) }

    Answer

    9 7 / user ada | base-kind / base 7

    The outer ID shadows the promoted one, and the explicit path reaches the embedded field.

  5. How is a name conflict between two embedded types resolved?

    Answer

    The selector is ambiguous and the compiler refuses it

    Both candidates are at the same depth, so there is no preference and the code must name one.

  6. What does the second line of this program print? package main import "fmt" type Base struct { ID int } func (b Base) Describe() string { return fmt.Sprintf("base %d", b.ID) } func (b Base) Kind() string { return "base-kind" } type User struct { Base ID int Name string } func (u User) Describe() string { return "user " + u.Name } func main() { u := User{Base: Base{ID: 7}, ID: 9, Name: "ada"} fmt.Println(u.ID, u.Base.ID) fmt.Println(u.Describe(), "|", u.Kind()) fmt.Println(u.Base.Describe()) }

    Answer

    9 7 / user ada | base-kind / base 7

    Describe is overridden by the outer type while Kind is promoted unchanged.

  7. What does the compiler say about this program? package main type A struct{} func (A) Name() string { return "a" } type B struct{} func (B) Name() string { return "b" } type C struct { A B } func main() { var c C _ = c.Name() }

    Answer

    ambiguous selector c.Name

    Both A and B provide Name at the same depth, so the selector is ambiguous.

  8. What does embedding an interface in a struct give the struct?

    Answer

    The interface's methods, delegated to the value in that field

    The embedded interface field supplies the methods; the struct only adds its own.

  9. What does this program print? package main import "fmt" type Logger interface { Log(string) } type console struct{} func (console) Log(s string) { fmt.Println("log:", s) } type Service struct { Logger Name string } func (s Service) Run() { s.Log("running " + s.Name) } func main() { s := Service{Logger: console{}, Name: "api"} s.Run() s.Logger.Log("direct call") }

    Answer

    log: running api / log: direct call

    Run calls the embedded logger, and the explicit path reaches the same value.

  10. What does a zero Service with an embedded Logger do when a method is called?

    Answer

    Panics, because the embedded interface is nil

    A nil interface has no dynamic type, so the delegated call panics; a constructor fills it.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image