douye9822 2017-06-26 13:20
浏览 8

如何在不返回的情况下更改函数中的切片?

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?

  • 写回答

1条回答 默认 最新

  • dongyili5843 2017-06-26 16:20
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号