您的位置 首页 golang

golang 切片在函数传递

背景: 切片当参数传递时,无法append

package mainfunc test(a []int){    a=append(a,1,2,3)  // print [89 4 5 6 1 2 3]}func main(){    var s []int=[]int{89,4,5,6}    test(s)    fmt.Println(s)}

原因: go语言中切片是地址传递,test函数添加的1,2,3后被分配了新的地址,s切片还是指向原来的地址,a和s内存地址不一样

image.png

解决方法:推荐方法2
1.在test函数返回新的切片,main函数接受返回结果

package mainimport "fmt"func test(a []int)(b []int){    b=append(a,1,2,3)    return}func main(){    var s []int=[]int{89,4,5,6}    s=test(s)    fmt.Println(s)}
  1. 在函数传递切片值(值的地址),&获取切片地址
package mainimport "fmt"func test(a *[]int){    *a=append(*a,1,2,3,7)  // *对指针取值    fmt.Printf("%p\n",&a)}func main(){    var s []int=[]int{89,4,5,6}        test(&s)  // &获取切片地址    fmt.Printf("%p\n",&s)    fmt.Println(s)}
image.png

文章来源:智云一二三科技

文章标题:golang 切片在函数传递

文章地址:https://www.zhihuclub.com/2906.shtml

关于作者: 智云科技

热门文章

网站地图