go学习(二十)传参


1、Slice传参

(1)slice 在函数传参时,使用指针。注意append 操作的“诡异”现象
append,必须传入slice的地址[]int类型才行,[]int时append无效。
modify,传入[]int和
[]int都可以,因此[]int就足够了。

func testModify1(s []int) {//有效
	s[0] = 10
}
func testModify2(s *[]int) {//有效
	(*s)[0] = 12
}
func testAppend1(s []int) {//无效
	s = append(s, 1)
}
func testAppend2(s *[]int) {//有效
	*s = append(*s, 1)
}
func main() {
	a := []int{1, 3, 4}
	testAppend1(a)
	fmt.Println(a)
	testAppend2(&a)
	fmt.Println(a)
	testModify1(a)
	fmt.Println(a)
	testModify2(&a)
	fmt.Println(a)
}
输出:
[1 3 4]
[1 3 4 1]
[10 3 4 1]
[12 3 4 1]

2、

参考:
https://blog.csdn.net/wang603603/article/details/121873640