什么是“值”数组?

huangapple go评论111阅读模式
英文:

What is a "value" array?

问题

在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?

答案1

得分: 1

在大多数情况下,它们与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.

答案2

得分: 0

自那时起(2010年),文章Slices: usage and internals更加精确:

> [4]int的内存表示只是按顺序排列的四个整数值:

什么是“值”数组?

> Go的数组是值。
数组变量表示整个数组;它不是指向第一个数组元素的指针(在C中是这样的)。
这意味着当你赋值或传递一个数组值时,你会复制它的内容。(为了避免复制,你可以传递一个指向数组的指针,但那是一个指向数组的指针,而不是一个数组。)
可以将数组视为一种带有索引而不是命名字段的固定大小的复合值

英文:

Since then (2010), the article Slices: usage and internals is a bit more precise:

> The in-memory representation of [4]int is just four integer values laid out sequentially:

什么是“值”数组?

> Go's arrays are values.
An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.)
One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.

答案3

得分: -1

在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

huangapple
  • 本文由 发表于 2010年6月27日 04:20:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/3125381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定