1

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.

1
  • Stop using terms like Base and Derived with Go. Go doesn't have inheritance and you'll just cause yourself grief by trying to think in terms of inheritance in a language which instead embraces composition. Commented Oct 2, 2015 at 15:16

2 Answers 2

5

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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.