字段:值和值初始化器的混合

huangapple go评论67阅读模式
英文:

mixture of field:value and value initializers

问题

为什么我不能使用匿名字段创建以下结构体?

type T1 struct {
    T1_Text string
}

type T2 struct {
    T2_Text string
    T1
}

在函数中使用:

t := T2{
    T2_Text: "Test",
    T1{T1_Text: "Test"},
}

为什么会出现"mixture of field:value and value initializers"的错误?

英文:

Why can I not create the following, with an anonymous field?

type T1 struct {
    T1_Text string
}

type T2 struct {
    T2_Text string
    T1
}

used in func ..

t := T2{
	T2_Text: "Test",
	T1{T1_Text: "Test"},
}

Gives me: mixture of field:value and value initializers?

答案1

得分: 81

简要解释。

你之所以得到这个结果,是因为你只能使用两种初始化器中的一种,而不能同时使用两种。

即,你可以使用 field:value 或者 value

以你的例子为例,你可以这样做:

field:value

t := T2{
    T2_Text: "Test",
    T1: T1{T1_Text: "Test"},
}

或者只使用值:

t := T2{
    "Test",
    T1{"Test"},
}

希望这样解释清楚了为什么。

英文:

A brief explanation.

The reason you get that is because you are allowed to only use one of the two types of initializers and not both.

i.e. you can either use field:value or value.

Using your example you either do

field:value

t := T2{
    T2_Text: "Test",
    T1: T1{T1_Text: "Test"},
}

or only values

t := T2{
    "Test",
    T1{"Test"},
}

Hope that explains the why

答案2

得分: 24

缺少属性名T1的赋值。

t := T2{
	T2_Text: "Test",
	T1:      T1{T1_Text: "Test"},
}

附注:只是将@twotwotwo的评论移动到了答案中。

英文:

Missing the attribute name T1 for assignment.

t := T2{
	T2_Text: "Test",
	T1:      T1{T1_Text: "Test"},
}

P.S. Just moved @twotwotwo's comment to an answer.

huangapple
  • 本文由 发表于 2014年12月24日 03:27:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/27626765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定