duanlan4801 2018-12-03 23:23
浏览 58
已采纳

在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. 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. 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.

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? 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.

  • 写回答

1条回答 默认 最新

  • dongtanxi5676756 2018-12-03 23:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?