我有这些类型:
type Value interface{}
type NamedValue struct {
Name string
Value Value
}
type ErrorValue struct {
NamedValue
Error error
}
我可以使用 v := NamedValue{Name: "fine", Value: 33}
,但我无法使用 e := ErrorValue {名称:“alpha”,值:123,错误:err}
好像嵌入语法没问题,但是用起来不行?
最佳答案
嵌入式类型是(未命名的)字段,由非限定类型名称引用。
A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name
T
or as a pointer to a non-interface type name*T
, andT
itself may not be a pointer type. The unqualified type name acts as the field name.
那就试试吧:
e := ErrorValue{NamedValue: NamedValue{Name: "fine", Value: 33}, Error: err}
如果您在复合文字中省略字段名称也可以:
e := ErrorValue{NamedValue{"fine", 33}, err}
尝试 Go Playground 上的示例.
关于Golang 嵌入式结构体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189605/