问题描述
我正在浏览slice tricks文档,看到一些衬里弹出。例如,这两个可以正常工作:
// pop
s := []int{1,2,3}
last,s := s[len(s)-1],s[:len(s)-1]
fmt.Println(last,s) // Prints 3 [1 2]
// pop front
s := []int{1,3}
first,s := s[0],s[1:]
fmt.Println(first,s) // Prints 1 [2 3]
但是,如果我尝试执行以下操作以弹出第二个元素:
s := []int{1,3}
second,s := s[1],append(s[0:1],s[2:]...)
fmt.Println(second,s) // Prints 3 [1 3]
它将弹出第二个元素,但是second
变量指向新切片中的第二个元素。为什么在这种情况下会发生这种情况,而在前两种情况下却没有呢?为了工作,我必须使用单独的行:
s := []int{1,3}
second := s[1]
s = append(s[0:1],s) // Prints 2 [1 3]
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)