Golang embedded struct type

后端 未结 3 1337
醉话见心
醉话见心 2020-12-03 03:07

I have these types:

type Value interface{}

type NamedValue struct {
    Name  string
    Value Value
}

type ErrorValue struct {
    NamedValue
    Error er         


        
3条回答
  •  无人及你
    2020-12-03 03:26

    Embedded types are (unnamed) fields, referred to by the unqualified type name.

    Spec: Struct types:

    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.

    So try:

    e := ErrorValue{NamedValue: NamedValue{Name: "fine", Value: 33}, Error: err}
    

    Also works if you omit the field names in the composite literal:

    e := ErrorValue{NamedValue{"fine", 33}, err}
    

    Try the examples on the Go Playground.

提交回复
热议问题