Go的泛型是什么?

编程入门 行业动态 更新时间:2024-10-26 02:32:55
本文介绍了Go的泛型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 最近有很多关于Golang的批评,因为它不支持泛型。这到底是什么意思呢?你如何解释这对于来自像Ruby这样的动态类型语言的人而言,这不是一个熟悉的概念? 解决方案

一个动态类型的语言,你不关心它是什么类型的列表,只是它是一个列表。但是,在静态类型语言中,您确实关心它是哪种类型的列表,因为类型是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的泛型是什么?

本文发布于:2023-11-09 10:30:13,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!