Golang 嵌入式结构类型
Golang embedded struct type
我有这些类型:
type Value interface{}
type NamedValue struct {
Name string
Value Value
}
type ErrorValue struct {
NamedValue
Error error
}
我可以使用v := NamedValue{Name: "fine", Value: 33}
,但我不能使用e := ErrorValue{Name: "alpha", Value: 123, Error: 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
, and T
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 上的示例。
加上icza的精彩回答。
你可以简单地这样做:
v := NamedValue{Name: "fine", Value: 33}
e := ErrorValue{NamedValue:v, Error: err}
而且效果很好。查看示例 Here
对于深层嵌套的结构,接受的答案的语法有点冗长。例如,这个:
package main
import (
"fmt"
)
type Alternative struct {
Question
AlternativeName string
}
type Question struct {
Questionnaire
QuestionName string
}
type Questionnaire struct {
QuestionnaireName string
}
func main() {
a := Alternative{
Question: Question{
Questionnaire: Questionnaire{
QuestionnaireName: "q",
},
},
}
fmt.Printf("%v", a)
}
可以这样重写:
a := Alternative{}
a.QuestionnaireName = "q"
我有这些类型:
type Value interface{}
type NamedValue struct {
Name string
Value Value
}
type ErrorValue struct {
NamedValue
Error error
}
我可以使用v := NamedValue{Name: "fine", Value: 33}
,但我不能使用e := ErrorValue{Name: "alpha", Value: 123, Error: 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 上的示例。
加上icza的精彩回答。
你可以简单地这样做:
v := NamedValue{Name: "fine", Value: 33}
e := ErrorValue{NamedValue:v, Error: err}
而且效果很好。查看示例 Here
对于深层嵌套的结构,接受的答案的语法有点冗长。例如,这个:
package main
import (
"fmt"
)
type Alternative struct {
Question
AlternativeName string
}
type Question struct {
Questionnaire
QuestionName string
}
type Questionnaire struct {
QuestionnaireName string
}
func main() {
a := Alternative{
Question: Question{
Questionnaire: Questionnaire{
QuestionnaireName: "q",
},
},
}
fmt.Printf("%v", a)
}
可以这样重写:
a := Alternative{}
a.QuestionnaireName = "q"