将嵌入的go结构体传递给函数。

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

Passing go embedded struct to function

问题

我有类似这样的代码:

  1. type Foo struct{}
  2. func NewFoo() *Foo { ... }
  3. type Bar struct {
  4. *Foo
  5. }

如何将一个 Bar 的实例传递给一个接受 *Foo 的函数?

  1. func DoStuff(f *Foo) {}
  2. func main() {
  3. bar := Bar{NewFoo()}
  4. DoStuff(bar) // <- go 不喜欢这样,类型不匹配
  5. }

有没有办法获取嵌入的结构并将其传递给函数?

我唯一能让这个工作的方法是将 *Foo 视为结构的成员,并将其作为 bar.foo 传递。但这有点混乱,这是唯一的方法吗?

英文:

I have something like this:

  1. type Foo struct{}
  2. func NewFoo() *Foo { ... }
  3. type Bar struct {
  4. *Foo
  5. }

How can I pass an instance of Bar to a function that takes *Foo?

  1. func DoStuff(f *Foo) {}
  2. func main() {
  3. bar := Bar{NewFoo()}
  4. DoStuff(bar) // &lt;- go doesn&#39;t like this, type mismatch
  5. }

Is it possible to get the embedded structure and pass it to the function?

The only way I can get this to work is if I treated *Foo as a member of the structure and passed it as bar.foo. But this is kind of messy, is that the only way?

答案1

得分: 11

匿名字段可以通过嵌入类型的名称进行访问:

  1. type Foo struct{}
  2. type Bar struct {
  3. *Foo
  4. }
  5. bar := Bar{&Foo{}}
  6. func(f *Foo) {}(bar.Foo)

请参阅语言规范中的结构类型部分。

英文:

Anonymous fields can be addressed by the name of the embedded type:

  1. type Foo struct{}
  2. type Bar struct {
  3. *Foo
  4. }
  5. bar := Bar{&amp;Foo{}}
  6. func(f *Foo) {}(bar.Foo)

See the Struct Types section in the language spec.

huangapple
  • 本文由 发表于 2016年12月3日 01:37:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/40937992.html
匿名

发表评论

匿名网友

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

确定