为什么 Go 中没有泛型? [英] Why no generics in Go?

查看:29
本文介绍了为什么 Go 中没有泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我现在只玩了一天围棋,所以很有可能我错过了很多.

Disclaimer: I've only played with Go for one day now, so there's a good chance I've missed a lot.

有谁知道为什么 Go 中没有对泛型/模板/whatsInAName 的真正支持?所以有一个通用的 map,但它是由编译器提供的,而 Go 程序员不能编写自己的实现.既然大家都在谈论让 Go 尽可能正交,为什么我可以使用泛型类型而不能创建新类型?

Does anybody know why there is no real support for generics/templates/whatsInAName in Go? So there is a generic map, but that's supplied by the compiler, while a Go programmer can't write her own implementation. With all the talk about making Go as orthogonal as possible, why can I USE a generic type but not CREATE a new one?

特别是在函数式编程方面,有 lambda 表达式,甚至闭包,但是对于缺少泛型的静态类型系统,我该如何编写像 filter(predicate, list) 这样的泛型高阶函数代码>?好的,链表等可以通过牺牲类型安全性的 interface{} 来完成.

Especially when it comes to functional programming, there are lambdas, even closures, but with a static type system lacking generics, how do I write, well, generic higher order functions like filter(predicate, list)? OK, Linked lists and the like can be done with interface{} sacrificing type safety.

由于对 SO/Google 的快速搜索没有揭示任何见解,看起来泛型(如果有的话)将作为事后的想法添加到 Go 中.我确实相信 Thompson 比 Java 人做得更好,但为什么要把泛型排除在外呢?或者他们已经计划好但尚未实施?

As a quick search on SO / Google did not reveal any insights, it looks like generics, if at all, will be added to Go as an afterthought. I do trust Thompson to do way better than the Java guys, but why keep generics out? Or are they planned and just not implemented yet?

推荐答案

你可以在这里找到这个答案:http://golang.org/doc/faq#generics

this answer you will find here: http://golang.org/doc/faq#generics

为什么 Go 没有泛型类型?

Why does Go not have generic types?

很可能会在某个时候添加泛型.我们不觉得他们有紧迫感,尽管我们知道有些程序员有.

Generics may well be added at some point. We don't feel an urgency for them, although we understand some programmers do.

泛型很方便,但它们的代价是类型系统和运行时的复杂性.我们还没有找到一种设计,其价值与复杂性成正比,尽管我们仍在继续思考.同时,Go 的内置映射和切片,以及使用空接口构造容器(显式拆箱)的能力意味着在许多情况下,如果不太顺利的话,可以编写执行泛型支持的代码.

Generics are convenient but they come at a cost in complexity in the type system and run-time. We haven't yet found a design that gives value proportionate to the complexity, although we continue to think about it. Meanwhile, Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly.

这仍然是一个悬而未决的问题.

This remains an open issue.

这篇关于为什么 Go 中没有泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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