什么是“价值”?大批?
在 C 语言中,数组的概念非常简单——只是指向内存中一行元素中第一个元素的指针,可以通过指针算术/标准 array[i]
语法来访问它。
然而,在像 Google Go 这样的语言中,“数组是值”,而不是指针。这意味着什么?它是如何实施的?
In C, the idea of an array is very straightforward—simply a pointer to the first element in a row of elements in memory, which can be accessed via pointer arithmetic/ the standard array[i]
syntax.
However, in languages like Google Go, "arrays are values", not pointers. What does that mean? How is it implemented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Go 中的数组也是值,因为它们作为值传递给函数(与整数、字符串、浮点等相同)
这需要为每个函数调用复制整个数组。
对于大型数组来说,这可能会非常慢,这就是为什么在大多数情况下通常最好使用切片
Arrays in Go are also values in that they are passed as values to functions(in the same way ints,strings,floats etc.)
Which requires copying the whole array for each function call.
This can be very slow for a large array, which is why in most cases it's usually better to use slices
从那时起(2010 年),文章 Slices:用法和内部 更加精确:
Since then (2010), the article Slices: usage and internals is a bit more precise:
在大多数情况下,它们与 C 数组相同,但编译器/解释器向您隐藏了指针。这主要是因为数组可以以完全透明的方式在内存中重新定位,因此此类数组似乎具有调整大小的能力。
另一方面,它更安全,因为如果无法移动指针,就无法进行泄漏。
In most cases they're the same as C arrays, but the compiler/interpreter hides the pointer from you. This is mainly because then the array can be relocated in memory in a totally transparent way, and so such arrays appear to have an ability to be resized.
On the other hand it is safer, because without a possibility to move the pointers you cannot make a leak.