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.
众所周知,当一个数组被创建时,会分配一 block 内存来保存这个数组包含的值:
(来源:golang.org)
C中的数组名指向第一个内存地址,然后它可以计算给定数组索引的地址并修改或读取该索引的值。但是这个文档说golang实现与此不同。
我很困惑 golang 方式有什么优势以及它如何实现它目前的方式。任何人都可以告诉我这方面的信息,非常感谢!
最佳答案
在 Golang 中,有 3 种类型可以处理数组。 (T = Go 中的任何类型,如字符串、整数等)(n = 自然数)
- 数组(固定数组)[n]T
var array [5]int array[1] = 2 fmt.Println(array)
slice (动态数组)[]T
map (关联数组)[T]T
Go 的数组是值。因为您只使用值,而键是自然数序列。 Golang 将数组长度保存在数组类型中,因为数组是固定的(声明后),Golang 可以创建一 block 具有数组长度的内存。
您也可以在这里询问有关 Golang 基础设施的问题。 https://github.com/golang/go/wiki/Questions
关于arrays - 为什么 Array 是 values 以及如何在 Golang 中实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191156/