切片作为参数传参,使用 append 后在函数内切边被修改了,而在主函数里面没有被改变
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.
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
-
56
Go的函数传递详解,一篇文章搞明白Golang的值传递。 继上篇文章后,继续来探讨下面的几个问题: 函数传参中值传递、指针传递与引用传递到底有什么不一样? 为什么说 slice 、
-
8
C++函数传参的时候,右引(T&&)和常引(const T&)接收的参数有什么不同,分别该什么时候用?登录一下,更多精彩内容等你发现贡献精彩回答,参与评论互动
-
7
线性结构是计算机最常用的数据结构之一。无论是数组(arrary)还是链表(list),在编程中不可或缺。golang也有数组,不同于别的语言,golang还提供了切片(slice)。切片比数组有更好的灵活性,具有某些动态特性。然而切片又不像动态语言的列表(Python list)...
-
5
【DB系列】Mybatis传参作为字段/表名时的注意事项 ...
-
3
V2EX › Go GO 语言中神秘的函数传参问题 cookgo · 2 天前 · 1744 次点击 首...
-
4
golang 中的切片(slice) 和 python 中的 list 很像,但是又有很多不一样的地方,本文总结一下,当某个函数的参数是切片类型的时候的一些特性。 数组作为函数的参数 package main import ( "fmt" ) func main() { a :...
-
8
golang中map与切片的函数传参 2022-08-13 Go
-
3
vue-router4 |name的作用|query传参|parmas传参|动态路由参数|命名视图|别名alias|前置路由守卫|路由过渡效果|滚动行为 vue-router4 出现 No match found for locat...
-
3
🚩write in front🚩 🔎大家好,我是謓泽,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎 🏅2021年度博客之星物联网与嵌入式开发TOP5~2021博客之星Top100~阿里云专家博主 & 阿里云星级博主~掘金⇿InfoQ~51CTOP创...
-
5
golang切片使用append函数的引用传递问题 zhuqingping · 大...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK