在没有泛型的情况下编写泛型函数 [英] Writing generics function without generics

查看:88
本文介绍了在没有泛型的情况下编写泛型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Go将来不会有泛型,并且有一些建议可以用其他结构代替它们。但是下面的例子让我陷入困境。

I know that Go will not have generics in the future and there are some recommendations to replace them by other constructs. But with my example below I got stuck.

func P(any interface{}, err error) (interface{}) {
    if err != nil {
        panic("error: "+ err.Error())
    }
    return any
}

您可能会猜到,我试图在发生任何错误时都失败,并想将 P()放在附近返回两个结果,第二个是错误的任何函数。这可以正常工作,但是任何会丢失其类型信息,并且结果中只是一个空接口。

As you might guess, I'm trying to just fail on any error and want to put P() just around any function that is returning two results and the second is an error. This is working fine, but any is losing it's type information and is only an empty interface in the result.

由于我也正在调用lib函数,因此我看不到用Interfaces或Reflection解决此问题的方法。

As I'm also calling lib functions I don't see a way to address this with Interfaces or Reflection.

有什么想法吗?我是完全走错了道路还是接近目标?

Any ideas? Am I totally on the wrong track or close to the goal?

推荐答案

一种解决方案是 开始生成 您的 P()函数,每种需要使用的具体类型之一。

请参见以下示例:

One solution would be to go generate your P() function, one for each concrete type you need to work with.
See examples in:

  • "Generic programming in Go using "go generate"".
  • "joeshaw/gengen"
  • "cheekybits/genny"
  • "clipperhouse/gen"
  • "Achieving type generic functions in Go, without using reflections"

这将使调用这些lib函数更加容易,因为生成的具体P()实现将使用正确的类型而不是界面{}。

That would make calling those lib functions easier, since the concrete P () implementations generated would use the right type instead of interface{}.

这篇关于在没有泛型的情况下编写泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆