Golang 嵌入式结构体类型

标签 go struct embedding composite-literals

我有这些类型:

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}

好像嵌入语法没问题,但是用起来不行?

最佳答案

嵌入式类型是(未命名的)字段,由非限定类型名称引用。

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.

那就试试吧:

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/

相关文章:

datetime - Golang - 结构 : time. 时间

go - 如何在 slice 上创建方法

c++ - 在运行时访问任何结构成员

python - 我怎样才能将 Lua 嵌入到 Python 3.x 中?

parsing - 嵌入mRuby : retrieving mrb_parser_message after parse error

go - golang代码有什么问题

go - 在后台运行并收集数据的 channel

swift - 在父类(super class)中实现 CodingKey 映射

c - atomic_bool 值更新,其他进程看不到

c++ - 在 C++ 中嵌入 python 时如何修复 "ImportError: No module named ' tensorflow'"