什么是“价值”?大批?

发布于 2024-09-07 16:52:03 字数 148 浏览 2 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回忆追雨的时光 2024-09-14 16:52:21

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

始于初秋 2024-09-14 16:52:18

从那时起(2010 年),文章 Slices:用法和内部 更加精确:

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

array in Go

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:

array in Go

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.

幼儿园老大 2024-09-14 16:52:15

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文