oopcode
oopcode

Reputation: 1962

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.

Upvotes: 1

Views: 485

Answers (2)

AndrewN
AndrewN

Reputation: 425

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)
}

Upvotes: 5

nessuno
nessuno

Reputation: 27042

To initialize composed objects you have to initialize the embedded field, like any other object:

package main

import (
    "fmt"
)

type Base struct {
    Field int
}

type Derived struct {
    Base
}

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

Upvotes: 1

Related Questions