go - go lang 中类似 slice 移位的函数

标签 go slice shift

数组移位函数如何与 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/

相关文章:

go - 更新 Go Web 应用程序的最佳实践

go - 测试包含调用 sql.Open 连接但没有数据库的 Golang 函数

go - 我的程序有什么错误?我已经使用了这些值?

arrays - Go slice 中的长度和容量

mysql 移动结果集底部的行

opencv - 如何在 JavaCV 中移动 Cvmat 的元素

go - 我无法使用以下代码检索访问 token

Golang slice append内置函数返回值

go - 使用要在运行时填充的字符串 slice

parsing - Bison 转移减少冲突,我不知道在哪里