GO语言开发中的坑:切片函数传参

1:切片作为函数传参

package main

import "fmt"


func test(target *[]int) {
	*target = append(*target, 1)
	fmt.Println(*target)
}
func test2(target []int) {
	target = append(target, 1)
	fmt.Println(target)
}

func main () {
	var tt = []int{4,5}
	test(&tt)
	fmt.Println(tt)
	fmt.Println("--------------")
	
	var tt2 = []int{4,5}
	test2(tt2)
	fmt.Println(tt2)
}

输出:

[4 5 1]
[4 5 1]
--------------
[4 5 1]
[4 5]

原因分析,加了一些打印如下:

package main

import "fmt"


func test(target *[]int) {
	fmt.Printf("process before:address of slice %p \n", *target)
	*target = append(*target, 1)
	fmt.Println(*target)
	fmt.Printf("process after:address of slice %p \n", *target)
}
func test2(target []int) {
	fmt.Printf("process before:address of slice %p \n", target)
	target = append(target, 1)
	fmt.Println(target)
	fmt.Printf("process after:address of slice %p \n", target)
}

func main () {
	var tt = []int{4,5}
	fmt.Printf("init:address of slice %p \n", tt)
	test(&tt)
	fmt.Println(tt)
	fmt.Printf("after:address of slice %p \n", tt)
	fmt.Println("--------------")
	
	var tt2 = []int{4,5}
	fmt.Printf("init:address of slice %p \n", tt)
	test2(tt2)
	fmt.Println(tt2)
	fmt.Printf("after:address of slice %p \n", tt2)
}

输出如下:

init:address of slice 0xc000016060 
process before:address of slice 0xc000016060 
[4 5 1]
process after:address of slice 0xc000014060 
[4 5 1]
after:address of slice 0xc000014060 
--------------
init:address of slice 0xc000014060 
process before:address of slice 0xc0000160a0 
[4 5 1]
process after:address of slice 0xc000014080 
[4 5]
after:address of slice 0xc0000160a0 

真相大白:

根据打印可以看出,切片直接传参,传的参数的切片结构体的副本,俩副本指向同样的底层数组。进过函数内部 append 操作后,切片重新生成,修改后的值无法传到函数外,修改无效。如果传的是切片地址,则操作对象一直是同一个结构体和底层数组。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值