gpt4 book ai didi

go - 延长长度并保持值(value)

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

我跟随 Go 之旅学习 GOLANG。

我在这一步有一个问题:https://tour.golang.org/moretypes/11

  package main

import "fmt"

func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)

// Step1 Slice the slice to give it zero length.
s = s[:0]
printSlice(s)

// Step2 Extend its length.
// Why after extend the length of the slice, the value in this slice is still [2 3 5 7]
s = s[:4]
printSlice(s)

// Step 3 Drop its first two values.
s = s[2:]
printSlice(s)
}

func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

输出:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

为什么在第二步扩展 slice 的长度后,这个 slice 中的值仍然是[2 3 5 7]?我认为这个 slice 中的值是 [0 0 0 0] 因为我在第一步已经 slice 了 origin slice 。

还有一个问题是,为什么第三步可以改变 slice 的容量,而第一秒却不能。

最佳答案

因为第一次扩展不会改变 slice 的指针地址。所以s也指向[2 3 5 7 11 13]地址。

package main

import (
"fmt"
"unsafe"
)

func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)

// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)

// Extend its length.
s = s[:4]
printSlice(s)

// Drop its first two values.
s = s[2:]
printSlice(s)
}

func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v array ptr: %v \n", len(s), cap(s), s,(*unsafe.Pointer)(unsafe.Pointer(&s)))
}

终端显示:

len=6 cap=6 [2 3 5 7 11 13] array ptr: 0xc04200a2a0
len=0 cap=6 [] array ptr: 0xc04200a2a0
len=4 cap=6 [2 3 5 7] array ptr: 0xc04200a2a0
len=2 cap=4 [5 7] array ptr: 0xc04200a2b0

你看,第三步更改了 ptr 地址,因为第一项已更改。所以你知道...

关于go - 延长长度并保持值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50713681/

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