英文:
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) // <- go doesn'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{&Foo{}}
func(f *Foo) {}(bar.Foo)
See the Struct Types section in the language spec.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论