迭代多个不同类型的数组的最佳方法

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

Best way to iterate over multiple arrays of different types

问题

我刚开始学习Go语言,我的编程背景是面向对象的。

举个例子,假设我有三个结构体:

type Parent struct {
    
}

type Foo struct {
    *Parent
}

type Bar struct {
    *Parent
}

FooBar结构体都继承自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 Parents?

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),那么在FooBar中嵌入Parent意味着它们也会实现相同的接口。这进而意味着你可以有一个接口类型的切片[]Baz,可以将ParentFooBar类型的值放入其中。需要注意的是,接口只能指定方法,而不能指定字段,因此当使用接口类型的值时,你只能访问接口的方法,而不能访问ParentFooBar中可能指定的任何字段。

英文:

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.

huangapple
  • 本文由 发表于 2017年7月22日 00:42:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/45242755.html
匿名

发表评论

匿名网友

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

确定