my code like this
package main
import(
"fmt"
)
func Pingpong(s []int){
fmt.Printf("len:%v,cap:%v,address:%p
",len(s),cap(s),s)
s=append(s,3)
fmt.Printf("len:%v,cap:%v,address:%p
",len(s),cap(s),s)
}
func main(){
s:=make([]int,1,2)
fmt.Printf("value:%v,len:%v,cap:%v,address:%p
",s[0],len(s),cap(s),s)
Pingpong(s)
fmt.Printf("value:%v,len:%v,cap:%v,address:%p
",s[0],len(s),cap(s),s)
}
the answer like this
value:0,len:1,cap:2,address:0x1040a128
len:1,cap:2,address:0x1040a128
len:2,cap:2,address:0x1040a128
value:0,len:1,cap:2,address:0x1040a128
Why? Could you please tell me the reason?
Notice how whenever you append to a slice in go, append
returns a new slice. This is because slices are backed by a fixed-size array, and multiple slices can be backed by the same array. In this case, append needs to return a new slice because the backing array may have changed. (For example creating a larger backing array to fit new items)
Your method is very similar to append
, and it has the same limitations. You'll need to return the new slice descriptor any time you modify the bounds. Basically any time you set your slice equal to something else, either by using append or taking a subslice, you have to return the new descriptor you made.