在古郎中编写仿制药物,不用泛型 [英] Writing generics function without generics in Go Lang

查看:139
本文介绍了在古郎中编写仿制药物,不用泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Go在将来不会有仿制药,而且有一些建议可以用其他的结构代替它们。但是,下面我的例子卡住了。

  func P(any interface {},err error)(interface {}){
if err!= nil {
panic(error:+ err.Error())
}
返回任何
}

您可能会猜到,我试图在任何错误上失败,并希望将 P()任何返回两个结果的函数,第二个是错误。这是正常的,但任何正在丢失它的类型信息,并且结果只是一个空的界面。



因为我也在调用lib函数,我没有看到一种解决这个接口或反射的方法。



任何想法?我完全在错误的轨道上或接近目标?

解决方案

一个解决方案是go生成 您的 P()函数,一个用于您需要使用的每个具体类型。

请参阅以下示例:





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


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
}

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.

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?

解决方案

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

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天全站免登陆