I was working on a sample program to answer another question here on SO and found myself somewhat baffled by the fact that the following code will not compile;
https://play.golang.org/p/wxBGcgfs1o
package main
import "fmt"
type A struct {
FName string
LName string
}
type B struct {
A
}
func (a *A) Print() {
fmt.Println(a.GetName())
}
func (a *A) GetName() string {
return a.FName
}
func (b *B) GetName() string {
return b.LName
}
func main() {
a := &A{FName:"evan", LName:"mcdonnal"}
b := &B{FName:"evan", LName:"mcdonnal"}
a.Print()
b.Print()
}
The error is;
/tmp/sandbox596198095/main.go:28: unknown B field 'FName' in struct literal
/tmp/sandbox596198095/main.go:28: unknown B field 'LName' in struct literal
Is it possible to set the value of fields from an embedded type in a static initializer? How? To me this seems like a compiler bug; if I didn't have the sources in front of me and was familiar with type I would be beating my head against a wall saying "clearly FName exists on B what is the compiler saying!?!?!".
Quickly, to preempt typical answers I am aware that the closest working syntax is this b := &B{A{FName:"evan", LName:"mcdonnal"}}
but that syntax is in my opinion conceptually contradictory to embedding so I would be disappointed if it is the only option. If this is the only way, is it a short coming of the Go compiler or is there actually a theoretical limitation that would prevent a compiler from interpreting the syntax in my non-working example?