我有以下内容:
https://play.golang.org/p/q2NUMzbw6-
package main
import "fmt"
type A struct {
Name string
Address string
}
type B struct {
A
}
type C struct {
A
}
type D struct {
A
}
//....more structs that embed A
type myinterface interface {
SetName(string)
SetAddress(string)
}
func run() *A {
// iterate over a slice of structs that embed A.... how????
for _, s := range []*A{
&B{}, &C{}, &D{},
} {
s.SetName("Bob")
s.SetAddress("Maine")
// do some other stuff that gets very verbose w/out a slice...
return s.A
}
}
func main() {
a := run()
fmt.Println(a)
}
我需要遍历所有嵌入 A 的结构,但我很难做到。以上不起作用“不能将 B 文字(类型 *B)用作数组或 slice 文字中的类型 *A”。什么是最好的方法?
最佳答案
在 A 上声明满足接口(interface)的方法:
func (a *A) SetName(s string) {
a.Name = s
}
func (a *A) SetAddress(s string) {
a.Address = s
}
在范围内使用该接口(interface)的一部分:
for _, s := range []myinterface{&B{}, &C{}, &D{}} {
...
}
关于go - 如何创建一个嵌入另一个结构的片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093551/