切片struct!=它实现的接口切片? [英] slice of struct != slice of interface it implements?
问题描述
我有一个接口Model
,由struct Person
实现.
I have an interface Model
, which is implemented by struct Person
.
要获取模型实例,我具有以下帮助函数:
To get a model instance, I have the following helper functions:
func newModel(c string) Model {
switch c {
case "person":
return newPerson()
}
return nil
}
func newPerson() *Person {
return &Person{}
}
以上方法使我可以返回类型正确的Person实例(以后可以使用相同的方法轻松添加新模型).
The above approach allows me to return a properly typed Person instance (can easily add new models later with same approach).
当我尝试执行类似的操作以返回模型切片时,出现错误.代码:
When I attempted to do something similar for returning a slice of models, I get an error. Code:
func newModels(c string) []Model {
switch c {
case "person":
return newPersons()
}
return nil
}
func newPersons() *[]Person {
var models []Person
return &models
}
Go抱怨:cannot use newPersons() (type []Person) as type []Model in return argument
我的目标是返回任何要求的模型类型的切片([]Person
,[]FutureModel
,[]Terminator2000
,w/e).我缺少什么,如何正确实施这样的解决方案?
My goal is to return a slice of whatever model type is requested (whether []Person
, []FutureModel
, []Terminator2000
, w/e). What am I missing, and how can I properly implement such a solution?
推荐答案
这与我刚刚回答的问题非常相似: https: //stackoverflow.com/a/12990540/727643
This is very similar to a question I just answered: https://stackoverflow.com/a/12990540/727643
简短的回答是您是正确的.一片结构不等于该结构实现的接口的一部分.
The short answer is that you are correct. A slice of structs is not equal to a slice of an interface the struct implements.
A []Person
和[]Model
具有不同的内存布局.这是因为它们是切片的类型具有不同的内存布局. Model
是一个接口值,这意味着在内存中它的大小为两个字.一个单词代表类型信息,另一个单词代表数据. Person
是一个结构,其大小取决于它包含的字段.为了从[]Person
转换为[]Model
,您将需要遍历数组并为每个元素进行类型转换.
A []Person
and a []Model
have different memory layouts. This is because the types they are slices of have different memory layouts. A Model
is an interface value which means that in memory it is two words in size. One word for the type information, the other for the data. A Person
is a struct whose size depends on the fields it contains. In order to convert from a []Person
to a []Model
, you will need to loop over the array and do a type conversion for each element.
由于此转换是O(n)操作,并且会导致创建新的切片,所以Go拒绝隐式地执行此操作.您可以使用以下代码明确地做到这一点.
Since this conversion is an O(n) operation and would result in a new slice being created, Go refuses to do it implicitly. You can do it explicitly with the following code.
models := make([]Model, len(persons))
for i, v := range persons {
models[i] = Model(v)
}
return models
并且正如 dskinner指出的,您很可能需要切片指针而不是切片指针.通常不需要指向切片的指针.
And as dskinner pointed out, you most likely want a slice of pointers and not a pointer to a slice. A pointer to a slice is not normally needed.
*[]Person // pointer to slice
[]*Person // slice of pointers
这篇关于切片struct!=它实现的接口切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!