gpt4 book ai didi

go - 带有 “reference semantics”的Go类型(例如 map , slice 和 channel )是否有通用名称?

转载 作者:行者123 更新时间:2023-12-03 10:09:12 26 4
gpt4 key购买 nike

根据Go: reference types as arguments中的响应和注释,Go似乎没有“正式”称为“引用类型”的类型。
但是,实际上有一些类型持有指向基础数据的指针,这些指针允许有效地将这些类型的值作为函数参数传递而无需使用指向它们的指针。当这样的值作为函数参数传递时,就不会(或者像 slice 那样很少)复制基础数据,因此,如果程序员采用指向该类型的指针并将其传递给它,则不会(或者非常少)提高效率。指针作为函数参数而不是值。
这些类型包括 slice 映射以及根据the accepted answer channel
官方的有效Go文档describes Slices为:

Slices hold references to an underlying array, and if you assign one slice to another, both refer to the same array. If a function takes a slice argument, changes it makes to the elements of the slice will be visible to the caller, analogous to passing a pointer to the underlying array.


Maps为:

Like slices, maps hold references to an underlying data structure. If you pass a map to a function that changes the contents of the map, the changes will be visible in the caller.


Channels为:

Like maps, channels are allocated with make, and the resulting value acts as a reference to an underlying data structure.


出于任何原因,文档似乎都避免针对这些类型使用术语“引用类型”,但在每种情况下仍然提及单词“引用”。
这些类型的特殊之处还在于,可以将 nil分配给该类型的值,类似于指针类型( doc):

A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
...

  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.

在日常程序员的实践中, 是重要的,它是了解,清楚地区分和清楚传达类型或数据结构的类型,这些类型或数据结构作为函数参数传递时共享基本数据,而不共享不共享(但复制)基础数据。
能够将 片段映射 channel 称为单个组,以便与其他(尤其是初级)程序员进行对话,这是清除通讯的一大优势,有助于确保程序中的数据安全并识别/防止连接的危险改变共享状态。
一般如何称呼这组类型?

最佳答案

How can this [slices, maps, functions and methods, and channels] group of types be called in general?


这个问题是不合理的,因为方法不是Go中的类型,而函数类型是函数,而仅仅是函数,不适合有关“引用”的讨论。
假设您想谈谈 slice , map ,闭包和缓冲 channel :
它们被称为“slice ,映射,闭包和缓冲 channel ”,可能不需要为这4个命名:它们没有太多共同点。
以下四种类型具有引用语义: slice ,映射,闭包和缓冲 channel 。 (没有缓冲的 channel 没有)。
  • slice 是一种值类型,用于显示支持数组的 View 。因此,它具有有关存储在后备数组中的值的引用语义。
  • 映射是一个映射,对于存储在映射中的值具有引用语义。 (这是最接近引用类型的。)
  • 函数关闭器是闭包,很复杂,根据值所有权与初级人员谈论它们可能没有帮助。
  • 缓冲 channel 显示有关缓冲值的引用语义。

  • 不需要一个复杂的术语(除非您从事学术工作并且分类,分离和分类是您的生活)。

    关于go - 带有 “reference semantics”的Go类型(例如 map , slice 和 channel )是否有通用名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65717235/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com