简体   繁体   English

在Go中传递任意切片

[英]Passing arbitrary slices in Go

I'm writing a function that retrieves arbitrary data from a database, and returns a slice of structs with the results. 我正在编写一个函数,该函数从数据库中检索任意数据,并返回包含结果的结构片段。 The data structure is defined by the user in an ItemFactory. 数据结构由用户在ItemFactory中定义。 The user then implements methods on the factory, that create empty structs: 然后,用户在工厂上实现创建空结构的方法:

func (t Example) GenerateEmptyItem() interface{} {
    return &Example{}
}

I am trying to do the same for slices of Example . 我试图对Example片段执行相同的Example I need to be able to use whatever is returned, to call functions such as len() , while at the same time, keeping it generic as to allow it to be returned by "generic" functions. 我需要能够使用返回的任何内容来调用len()函数,同时保持其通用性,以允许其由“通用”函数返回。

I can't simply have something like this, as the underlying data allocation for a slice of interfaces is different from a slice of Examples: 我不能简单地拥有这样的东西,因为对一片接口的基础数据分配与一系列示例不同:

func (t Country) GenerateEmptyItems() []interface{} {
    return []Country{} //Error
}

Is it possible to use a pointer to a slice, such as &[]Example{} and pass it as an interface{} , and then still be able to use it as a slice? 是否可以使用指向切片的指针,例如&[]Example{}并将其作为interface{}传递,然后仍然可以将其用作切片? Or am I going about this wrong?.Remember, I don't know the type of the data at compile-time, so I can't simply cast. 还是我要解决这个错误?记住,我在编译时不知道数据的类型,所以我不能简单地进行转换。

I appreciate any help. 感谢您的帮助。 Let me know if I can clarify anything. 让我知道是否可以澄清任何事情。

You can't quite do this directly. 您不能完全直接这样做。

You can use reflection , however this isn't a great solution. 您可以使用反射 ,但这不是一个很好的解决方案。 The normal way is to have an interface type defined that lets you interact with all the data in the same way. 通常的方法是定义一个接口类型,让您以相同的方式与所有数据进行交互。 A good example of this is the sort package. 排序包就是一个很好的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM