4

切片作为参数传参,使用 append 后在函数内切边被修改了,而在主函数里面没有被改变

 2 years ago
source link: https://www.v2ex.com/t/813641
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Go 编程语言

切片作为参数传参,使用 append 后在函数内切边被修改了,而在主函数里面没有被改变

  yagamil · 8 小时 47 分钟前 · 81 次点击
package main

import "fmt"

func main() {
        arr := make([]int, 3, 4)             //创建一个长度为 3 ,容量为 4 的切片
        fmt.Println(arr, len(arr), cap(arr)) //[0 0 0] 3 4
        // -----
        fmt.Printf("%p\n", arr)
        addNum(arr)
        // -----
        fmt.Println(arr, len(arr), cap(arr)) //[0 0 0] 3 4
        fmt.Printf("%p\n", arr)
}

func addNum(sli []int) {
        fmt.Printf("%p\n", sli)
        sli = append(sli, 4)
        fmt.Println(sli, len(sli), cap(sli)) //[0 0 0 4] 4 4
        fmt.Printf("%p\n", sli) 
}

看到网上的解释是, 在 addNum 里面,sli 的底层数组是的确被修改了,可是切片的 len 由于是值复制,所以切片的 len 没有被修改,导致外层 main 里面的切片没有被显示?

如果是这样,那么应该传参的时候传入的切片地址应该不一样才对,因为是传值,传入的是切片结构体的拷贝值,而不应该是切片的原地址。

type slice struct {
	array unsafe.Pointer //存储数组指针
	len   int
	cap   int
}

望大神指点。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK