gpt4 book ai didi

arrays - slice 在 GO 中是如何工作的?

转载 作者:IT王子 更新时间:2023-10-29 02:12:36 25 4
gpt4 key购买 nike

a = make([]int, 7, 15)

创建大小为 15 的隐式数组,slice(a) 创建隐式数组的浅拷贝并指向数组中的前 7 个元素。

考虑一下,

var a []int;

创建一个不指向任何隐式数组的零长度 slice 。

a = append(a, 9, 86);

创建长度为 2 的新隐式数组并附加值 986。 slice(a) 指向新的隐式数组,其中

len(a) 为 2cap(a) >= 2


我的问题:

这样理解对吗?

最佳答案

正如我提到的“Declare slice or make slice?”, slice 的零值 (nil) 就像一个零长度 slice 。

因此您可以直接附加到 a []int

仅当您希望可能返回一个空 slice (而不是nil)时,您才需要创建一个 slice (make([]int, 0) )。
如果不是,则无需在开始追加之前分配内存。
另见“Arrays, slices (and strings): The mechanics of 'append': Nil

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

关于arrays - slice 在 GO 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906439/

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