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.

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

报告相同问题?

悬赏问题

  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测