问题
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?
回答1:
It's not a compiler bug but a design decision. The language spec just states:
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
I guess the reasoning behind this is to avoid ambiguity. There are a few rules to resolve name conflicts when using selectors, and they would have to be complicated in order to allow what you're suggesting. On top of that, it might create ambiguity if you're using an existing instance of an embedded struct inside a struct literal of the embedding type.
EDIT: Here's an example where this approach might backfire:
Think of a case where you have A embedding B, and an instance of A you want to embed:
type A {
X int
}
type B {
A
}
It's simple enough to do
b := B{ X: 1 }
And infer what should be done. But what if we already have an instance of A? This doesn't make sense:
a := A { X: 1 }
b := B { X: 2, A: a, }
are you first assigning 2 to a zero instance of A and then assigning the initialized instance of A over it? And is it identical to:
b := B { A: a, X: 2 } ?
It breaks the assumption that initialization order is irrelevant in a composite literal with field names.
来源:https://stackoverflow.com/questions/29979056/composite-literal-and-fields-from-an-embedded-type