一个动态类型的语言,你不关心它是什么类型的列表,只是它是一个列表。但是,在静态类型语言中,您确实关心它是哪种类型的列表,因为类型是A的列表,其中A是某种类型。也就是说,列表A 与列表B 不同。
所以当你谈到泛型时,调用 A - >类型的函数。 B 具有 foreach 的列表中的每一项都意味着该列表必须是列表A 。但是,如果您使用泛型,那么您不必声明 A 是什么,您可以在稍后的日期填写它。因此,你建立了一个合同,给定一个列表C 和一个函数 A - > B , A === C 以便编译。这大大减少了样板。 在Go中,由于缺乏泛型以及声明这种类型合约的能力,您必须编写一个函数,该函数在int列表上运行, double,字符串列表等等。你不能以通用方式定义事物。
There's been a lot of criticism about Golang recently because it doesn't have support for generics. What exactly does that mean? How would you explain that to someone coming from a dynamically typed language like Ruby where this isn't a familiar concept?
解决方案In a dynamically typed language, you don't care what type of list it is, just that it's a list. However, in a statically typed language, you do care what type of list it is because the type is "a list of A" where "A" is some type. That is, a list A is a different type from list B.
So when you speak of generics, calling some function of type A -> B each item of a list with a foreach means that the list must be a list A. But... if you use generics, then you don't have to declare what A is, you can just have it be filled in at a later date. Thus, you establish the contract whereby given a list C and a function A -> B, A === C in order for it to compile. This reduces boilerplate considerably.
In Go, given the lack of generics and the ability to declare such a type contract, you have to write a function that operates on a list of int, a list of double, a list of string, etc. You can't just define things in a "generic" manner.
更多推荐
Go的泛型是什么?
发布评论