Search code examples
goembedding

Go: embedded type's field initialization in derived type


Here is the code that works:

package main

import (
    "fmt"
)

type Base struct {
    Field  int
}

type Derived struct {
    Base
}

func main() {
    d := &Derived{}
    d.Field = 10
    fmt.Println(d.Field)
}

And here's the code that fails to compile with ./main.go:17: unknown Derived field 'Field' in struct literal

package main

import (
    "fmt"
)

type Base struct {
    Field  int
}

type Derived struct {
    Base
}

func main() {
    d := &Derived{
        Field: 10,
    }
    fmt.Println(d.Field)
}

What exactly is going on here? Sorry if it's obvious, but I just don't understand.


Solution

  • From the language specification:

    Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

    So that's why it doesn't work.

    Here are two possible ways to work around that limitation, each illustrated in the following function:

    func main() {
        d := &Derived{
            Base{Field: 10},
        }
    
        e := new(Derived)
        e.Field = 20
    
        fmt.Println(d.Field)
        fmt.Println(e.Field)
    }