构造包含嵌套结构的结构体字面量。

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

Construct struct literal with embedded structs

问题

如何使用嵌套结构构造结构体字面值?

Go代码示例:

package main

import "fmt"

type Ping struct {
    Content struct {
        name string
    }
}

func main() {
    p := Ping{Content{"hello"}}
    fmt.Println(p)
}

如果我按照以下方式编写结构体,它将起作用:

Go代码示例:

type Ping struct {
    Content
}

type Content struct {
    name string
}

如何在第一个代码版本中使用嵌套结构体版本实现这一点?

英文:

How do I construct a struct literal with embedded struct?

Go:

package main

import "fmt"

type Ping struct {
    Content struct {
    	name string
    }
}

func main() {
   p := Ping{Content{"hello"}}
   fmt.Println(p)
}

http://play.golang.org/p/UH4YO6CAFv

This works if I had written the structs this way:

Go:

type Ping struct {
   Content
}

type Content struct {
    name string
}

http://play.golang.org/p/ERGsO4CMEN

How do I do it with the embedded struct version in the first code version?

答案1

得分: 3

你不能这样做,而且你真的不应该这样做,但如果你坚持,你可以使用类似以下的代码:

p := Ping{struct{ name string }{"不要这样做"}}

或者

p := Ping{}
p.Content.name = "你好"

playground

英文:

You can't, and you really shouldn't either, but if you insist anyway you can use something like:

p := Ping{struct{ name string }{"don't do it"}}

or

p := Ping{}
p.Content.name = "hello"

<kbd>playground</kbd>

答案2

得分: 3

这似乎不受支持,查看Struct类型的规范

声明了类型但没有显式字段名的字段是匿名字段,也称为嵌入字段或将类型嵌入结构体中。嵌入的类型必须被指定为类型名T或非接口类型名*T的指针,而T本身不能是指针类型。

这意味着T必须在其他地方定义。

英文:

This doesn't seem to be supported, looking at the spec for Struct type

> 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.

That means T must be defined somewhere else.

huangapple
  • 本文由 发表于 2014年9月24日 14:18:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/26009865.html
匿名

发表评论

匿名网友

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

确定