【问题标题】:How to move a value in a slice to the last position in Golang? [duplicate]如何将切片项目移动到 Golang 中的最后一个位置?
【发布时间】:2022-10-21 12:43:34
【问题描述】:

我想知道如何正确地将切片元素移动到 Golang 中切片的最后一个位置。

例如:

func main() {
    slc := []int{1,2,3,4,5}
    fmt.Println(shiftEnd(slc,2))
}

func shiftEnd(s []int, x int) []int {
return append(s[x:],s[:x]...)
}

这将导致[3,4,5,1,2] 我想知道如何接收[1,3,4,5,2]

Playground

【问题讨论】:

    标签: go slice


    【解决方案1】:

    我正在使用这个 sn-p 解决方案,但我仍在寻找更好的替代方案:

    func main() {
        s := []int{1, 2, 3, 4, 5}
        fmt.Println(shiftEnd(s, 2))
    
    }
    
    func shiftEnd(s []int, x int) []int {
        if len(s) < 1 {
            fmt.Println("No Enought Values")
            return s
        }
    
        if s[len(s)-1] == x {
            fmt.Println("Already in the end")
            return s
        }
        return append(append(s[:x-1], s[x:]...), x) //same as before but in a smaller snippet
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2013-12-10
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      相关资源
      最近更新 更多