英文:
Best way to iterate over multiple arrays of different types
问题
我刚开始学习Go语言,我的编程背景是面向对象的。
举个例子,假设我有三个结构体:
type Parent struct {
}
type Foo struct {
*Parent
}
type Bar struct {
*Parent
}
Foo
和Bar
结构体都继承自Parent
。如果我有一个Foo
结构体的数组和一个Bar
结构体的数组,有没有办法将它们合并成一个包含Parent
的数组或切片呢?
如果没有的话,那么如果我知道我只会访问从Parent
继承的属性,那么同时遍历这两个数组的最佳方法是什么?
英文:
I just started learning Go and I come from a background of OOP.
So for example, say I have three structs like so:
type Parent struct {
}
type Foo struct {
*Parent
}
type Bar struct {
*Parent
}
The Foo and Bar structs both extend Parent. If I have an array of Foo
's, and an array of Bar
's, is there a way to merge these into a single array/slice of Parent
s?
If not, then what is the best way to iterate over the two arrays at once if I know I will only be accessing properties inherited from Parent
?
答案1
得分: 3
Go语言不支持继承,它仅支持接口作为多态的实现方式。在示例代码中,所使用的是嵌入(embedding),它并不提供多态性;如果在Foo
中嵌入Parent
,这并不能让你将Foo
类型的值赋给Parent
类型的变量或切片。
你可以接近实现你所描述的需求,使用接口。如果Parent
实现了某个接口(比如Baz
),那么在Foo
和Bar
中嵌入Parent
意味着它们也会实现相同的接口。这进而意味着你可以有一个接口类型的切片[]Baz
,可以将Parent
、Foo
或Bar
类型的值放入其中。需要注意的是,接口只能指定方法,而不能指定字段,因此当使用接口类型的值时,你只能访问接口的方法,而不能访问Parent
、Foo
或Bar
中可能指定的任何字段。
英文:
Go does not support inheritance, and the only polymorphism it supports is interfaces. What you've got in the example code is called embedding, and it does not offer polymorphism; if you embed Parent
in Foo
, that does not let you assign a Foo
-type value to a Parent
-type variable or slice.
The closest you can get to what you describe would be using interfaces. If Parent
implements some interface (let's say Baz
), then embedding Parent
in Foo
and Bar
means that both will also implement that same interface. This in turn means that you can have a slice of the interface type []Baz
into which you could put values of type Parent
, Foo
, or Bar
. Note that interfaces can only specify methods, not fields, so when using values of the interface type, you'll only be able to access the methods of the interface, not any fields that might be specified in Parent
, Foo
, or Bar
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论