gpt4 book ai didi

go - 生长 slice 和底层数组

转载 作者:IT王子 更新时间:2023-10-29 01:51:30 26 4
gpt4 key购买 nike

我有一个数组和一个指向它的 slice ,如下所示:

package main

import "fmt"

func main() {

array_str := []string{"0a","1b","2c","3d","4e"}
slice_str:=array_str[1:4]
fmt.Println("Initially :")
fmt.Println("Printing 1 :Array :",array_str)
fmt.Println("Printing 1 :Slice:",slice_str)

//Step 1.Changing Slice and it get reflected in array
fmt.Println("\nAfter Alteration:")
slice_str[0]="alterd_1b"
fmt.Println("Printing 2 :Array :",array_str)
fmt.Println("Printing 2 :Slice:",slice_str)
fmt.Println("len of slice_str:",len(slice_str)," cap of slice_str:",cap(slice_str),"len of array_str:",len(array_str))

//Step 2.appending to slice and it get reflected

slice_str = append(slice_str,"apnded_elemnt")
fmt.Println("\nAfter Apending:")
fmt.Println("Printing 3 :Array :",array_str)//"4e" is replaced with "apnded_elemnt" in array !!
fmt.Println("Printing 3 :Slice:",slice_str)
fmt.Println("len of slice_str:",len(slice_str)," cap of slice_str:",cap(slice_str),"len of array_str:",len(array_str))

//Step 3.Again appending to slice so that lentght of slice is growing further to underlaying array
slice_str = append(slice_str,"outgrown_elemnt")
fmt.Println("\nAfter OUT GROWING:")
fmt.Println("Printing 4 :Array :",array_str)//obeviously out grown elemnt not added to array that is fine
fmt.Println("Printing 4 :Slice:",slice_str)
fmt.Println("len of slice_str:",len(slice_str)," cap of slice_str:",cap(slice_str),"len of array_str:",len(array_str))
//How Capacity Become 8 here ???

//Step 4 .Now Changing Slice element which is in Range of array to verify it reflect on array:
fmt.Println("\nAfter Post out grown Alteration:")
slice_str[0]="again_alterd_1b"
fmt.Println("Printing 2 :Array :",array_str)//Change in slice is not reflectd in array .Why ?
fmt.Println("Printing 2 :Slice:",slice_str)
}

Playground :http://play.golang.org/p/3z52HXHQ7s

问题:

  1. 在第 3 步中:为什么 slice 的 cap 从 4 跳到 8?

  2. 在第 4 步中:在 slice 长大后,对数组范围内的 slice 元素的更改不会反射(reflect)到数组中,反之亦然.为什么长大后就没有了?当 slice 长出来时究竟发生了什么?

最佳答案

参见此处:http://blog.golang.org/slices

简短的回答:1) 它通过加倍增长(虽然很短)。如果您追加一次,您也可能会追加第二次,这样可以避免分配。 2)这就是 slice 增长的工作原理。一个数组不能增长,所以分配一个新的、更大的数组,复制旧的数组,然后你得到一个指向更大副本的 slice 。

(golang.org 网站上的文档非常有帮助,可读性强,简短而准确。我建议您先查看 golang.org,然后再在这里提问。)

关于go - 生长 slice 和底层数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212260/

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