英文:
I want to use generics in golang but I dont want to upgrade it to 1.18 or later. Is there any way?
问题
我想在我的Go代码中使用类似于func abc[T any](collections []T)
的东西,但是它报错了:
类型参数需要go1.18或更高版本
我不想升级到1.18或更高版本。有没有其他办法?
英文:
I want to make use of something like func abc[T any](collections []T)
in my Go code but it throws error:
> type parameters require go1.18 or later
I don't want to upgrade it to 1.18 or later. Is there any way?
答案1
得分: 2
从技术上讲,你可以使用开发标志在Go 1.17上编译一些通用代码,但是会有严重的限制。然而,没有任何充分的理由去这样做。
唯一明智和直接的做法是升级到Go 1.18。
英文:
Technically yes, you could get some generic code to compile — with severe limitations — on Go 1.17, using dev flags; however there is no good reason to do that, whatsoever.
The only sensible and straightforward thing to do is to upgrade to Go 1.18.
答案2
得分: -1
你可以尝试找一个泛型预处理器。例如,这里有一个非常过时的例子(我自己没有使用过)。你使用的是哪个版本的Go?你能提供一些关于为什么你不升级到1.18的详细信息吗?
https://github.com/diffeo/gogen
正如其他人所说,我要警告你,使用这样的东西而不是升级到1.18可能会有问题。一旦项目有其他人参与,很少有人会知道如何管理它。
另一个选择是你可以使用any
与类型断言/反射一起使用。虽然你可以做一些"泛型"的事情,但这会导致代码难以管理,再次考虑升级到1.18。
英文:
@mohit-singla you can try to find a generics preprocessor. For example, here is a very dated example of one (I have not used myself). Which version of Go are you using? Can you provide details on why you are holding off 1.18?
https://github.com/diffeo/gogen
As others have stated, I would warn you about using something like this instead of upgrading to 1.18. Once the project has other people involved, few people will know how to manage it.
Another alternative is for you use any
along with type assertion/reflection. While you can do "generic" things, it makes for less manageable code, again look to 1.18.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论