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

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

Passing go embedded struct to function

问题

我有类似这样的代码:

type Foo struct{}
func NewFoo() *Foo { ... }

type Bar struct {
    *Foo
}

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

func DoStuff(f *Foo) {}

func main() {
    bar := Bar{NewFoo()}
    DoStuff(bar) // <- go 不喜欢这样,类型不匹配
}

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

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

英文:

I have something like this:

type Foo struct{}
func NewFoo() *Foo { ... }

type Bar struct {
    *Foo
}

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

func DoStuff(f *Foo) {}

func main() {
    bar := Bar{NewFoo()}
    DoStuff(bar) // &lt;- go doesn&#39;t like this, type mismatch
}

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

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

type Foo struct{}

type Bar struct {
	*Foo
}

bar := Bar{&Foo{}}

func(f *Foo) {}(bar.Foo)

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

英文:

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

type Foo struct{}

type Bar struct {
	*Foo
}

bar := Bar{&amp;Foo{}}

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:

确定