gpt4 book ai didi

go - 如何优雅地使 slice 追加安全

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:20 26 4
gpt4 key购买 nike

slice := []int{10, 20, 30, 40, 50,60}

newSlice := slice[2:4:5]



fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

newSlice = append(newSlice,70)

fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

newSlice = append(newSlice,80)

fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

输出将是

old slice is [10 20 30 40 50 60] 
new slice is [30 40]
old slice is [10 20 30 40 70 60]
new slice is [30 40 70]
old slice is [10 20 30 40 70 60]
new slice is [30 40 70 80]

追加有不同的行为。我知道导致追加有不同行为的原因。因为新分片容量大于length时新旧共享数组,但是append 80,容量不够大,所以创建了一个新数组。所以检查容量将避免附加有不同的行为或者我可以定义新的 slice newSlice := slice[2:4:4]

有什么优雅的解决方案吗?因为每次append之前check有点难看,而且在某些情况下希望新老一直共享slice。如何让它优雅地发生?

最佳答案

这是一个非常好的随机 slice 资源:https://github.com/golang/go/wiki/SliceTricks

在这种情况下,我建议先创建一个新 slice ,然后每次都添加元素,如下所示:

slice := []int{10, 20, 30, 40, 50, 60}

newSlice := make([]int, 0)
newSlice = append(newSlice, slice[2:4:5]...)

fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

newSlice = append(newSlice, 70)

fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

newSlice = append(newSlice, 80)

fmt.Printf("old slice is %d \n", slice)
fmt.Printf("new slice is %d \n", newSlice)

结果是:

old slice is [10 20 30 40 50 60] 
new slice is [30 40]
old slice is [10 20 30 40 50 60]
new slice is [30 40 70]
old slice is [10 20 30 40 50 60]
new slice is [30 40 70 80]

关于go - 如何优雅地使 slice 追加安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949954/

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