数组移位函数如何与 slice 一起使用?
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
for k, v := range s {
x, a := s[0], s[1:] // get and remove the 0 index element from slice
fmt.Println(a) // print 0 index element
}
}
我从 slice 技巧中找到了一个示例,但无法正确理解。
https://github.com/golang/go/wiki/SliceTricks
x, a := a[0], a[1:]
<小时/>
编辑您能解释一下为什么 x 在这里未定义吗?
基于答案并与 SliceTricks 合并
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println(len(s), s)
for len(s) > 0 {
x, s = s[0], s[1:] // undefined: x
fmt.Println(x) // undefined: x
}
fmt.Println(len(s), s)
}
最佳答案
例如,
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println(len(s), s)
for len(s) > 0 {
x := s[0] // get the 0 index element from slice
s = s[1:] // remove the 0 index element from slice
fmt.Println(x) // print 0 index element
}
fmt.Println(len(s), s)
}
输出:
6 [2 3 5 7 11 13]
2
3
5
7
11
13
0 []
引用文献:
The Go Programming Language Specification: For statements
<小时/>回答编辑问题的附录:
声明x
,
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println(len(s), s)
for len(s) > 0 {
var x int
x, s = s[0], s[1:]
fmt.Println(x)
}
fmt.Println(len(s), s)
}
输出:
6 [2 3 5 7 11 13]
2
3
5
7
11
13
0 []
您可以为任何 slice 类型复制并粘贴我的代码;它推断 x 的类型。如果 s
的类型发生变化,则不必更改它。
for len(s) > 0 {
x := s[0] // get the 0 index element from slice
s = s[1:] // remove the 0 index element from slice
fmt.Println(x) // print 0 index element
}
对于您的版本,x
的类型是显式的,如果 s
的类型发生更改,则必须更改。
for len(s) > 0 {
var x int
x, s = s[0], s[1:]
fmt.Println(x)
}
关于go - go lang 中类似 slice 移位的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42730031/