Golang嵌入式结构类型 [英] Golang embedded struct type

查看:154
本文介绍了Golang嵌入式结构类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型:

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}

I can use use v := NamedValue{Name: "fine", Value: 33}, but I am not able to use e := ErrorValue{Name: "alpha", Value: 123, Error: err}

似乎可以嵌入语法,但不能使用它吗?

Seems that embedding syntax was ok, but using it doesn't work?

推荐答案

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

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

规范:结构类型:


用类型声明的字段但没有明确的字段名称是匿名字段,也称为 embedded 字段或该类型在结构中的嵌入。必须将嵌入式类型指定为类型名称 T 或指向非接口类型名称 * T 的指针, T 本身可能不是指针类型。 不合格的类型名称充当字段名称。

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}

如果您省略复合文字中的字段名称,也可以使用:

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

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

转到游乐场上尝试示例。

这篇关于Golang嵌入式结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆