英文:
Does Go support templates or generics?
问题
我知道Go语言在传统的面向对象编程(OOP)中没有类的概念,但是Go提供了接口的概念,可以实现大部分你想要做的面向对象编程的功能。
但是,Go是否允许创建类似于模板类的东西呢?例如,我正在阅读container/list包的源代码。它定义了一个列表和列表的相关方法。但是在所有方法中,列表中包含的值的类型都是interface{}
,也就是任意类型。是否有办法创建一个只能容纳特定类型值的列表?比如int、string、Fruit等。
英文:
I know that Go doesn't have classes in the traditional OOP sense, but Go does provide a notion of interfaces that allows you do most of the OOP things you'd want to do.
BUT, does Go allow for something like creating a templated class? For instance, I'm reading through the source code for the container/list package. It defines a list and the list's associated methods. But in all methods, the values contained in the list are of type interface{}
-- so, of any type. Is there any way to create a list that is constrained to only hold values of a particular type? int, string, Fruit... whatever.
答案1
得分: 5
比gotgo更新的是一个基于代码生成的包,叫做"gen"。
http://clipperhouse.github.io/gen/
gen是一个试图在Go语言中引入类似泛型功能的尝试,灵感来自于C#的Linq、JavaScript的Array方法和underscore库。操作包括过滤、分组、排序等等。
模式是像在Linq中传递lambda表达式或在JavaScript中传递函数一样传递func。
英文:
Newer than gotgo, there's a code-generation-based package called "gen".
http://clipperhouse.github.io/gen/
> gen is an attempt to bring some generics-like functionality to Go, with inspiration from C#’s Linq, JavaScript’s Array methods and the underscore library. Operations include filtering, grouping, sorting and more.
>
> The pattern is to pass func’s as you would pass lambdas in Linq or functions in JavaScript.
答案2
得分: 3
基本上是 @FUZxxl 所说的。
泛型?目前还不支持。
模板?不完全是。有第三方项目,比如 gotgo,旨在通过预处理文件来添加模板支持。然而,据我所知,gotgo 已经停止维护了。
目前你最好的选择是使用接口或反射。
如果你真的想使用反射,请注意 reflect
包提供了一种方法来使用泛型(反射)内容填充一个有类型的函数变量。你可以使用这个方法来在基于反射的解决方案中使用编译器可以检查的类型。
英文:
Basically what @FUZxxl said.
Generics? Not at this time.
Templates? Not quite. There are third-party projects like gotgo which aim to add template
support by pre-processing files. However, gotgo is quite dead as far as I know.
Your best option is to use interfaces or reflection for the time being.
If you really want to use reflection, note that the reflect
package offers a way to fill a typed function variable with generic (reflected) content. You can use this to use types the compiler
can check with your reflection based solutions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论