gpt4 book ai didi

arrays - 我如何在go中找到数组的大小

转载 作者:IT王子 更新时间:2023-10-29 00:33:34 25 4
gpt4 key购买 nike

我试过 len() 函数,但它给出了声明的值。 size() 函数出错。

代码:

package main
var check [100]int
func main() {
println(len(check))
}

这里的输出是 100,我需要数组中的所有项(即 0)。

最佳答案

Go 中的数组是固定大小的:一旦您在 Go 中创建了一个数组,您以后就不能更改它的大小。在某种程度上,数组的长度是数组类型的一部分(这意味着类型 [2]int[3]int 是两种不同的类型).也就是说,某些数组类型的值的长度始终相同,并且由其类型决定。例如,类型为 [100]int 的数组值的长度始终为 100(可以使用内置函数 len() 查询)。

Spec: Array Types:

The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int. The length of array a can be discovered using the built-in function len.

如果您正在寻找“已设置了多少个元素?”的答案,Go 中不会对此进行跟踪。您正在寻找的“数组中的项目总数”也始终与数组长度相同:当您在 Go 中创建数组时,数组中的所有元素都被初始化为 zero-value。元素的类型(除非另有说明,例如使用 composite literal )。

例如在这一行之后:

var arr [100]int

数组 arr 已经有 100 个 int,都是 0(因为那是 int 类型的零值)。在以下行之后:

var arr2 = [3]int{1, 2, 3}

数组arr2有3个int元素,分别是123。在下一行之后

var arr3 = [...]bool{3: true}

数组arr3有4个bool元素,分别为false, false, falsetrue(falsebool 类型的零值,我们只指定第 4 个元素为 true 位于索引 3)。

如果您询问 slices,您的问题可能更有意义:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

所以基本上, slice 是数组某些(连续)部分的“ View ”。 slice 头或描述符包含一个指向它在数组中描述的部分的第一个值的指针,它包含一个长度和容量(这是长度可以扩展到的最大值)。

我强烈推荐阅读以下博文:

The Go Blog: Go Slices: usage and internals

The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

关于arrays - 我如何在go中找到数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35937828/

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