dongxing1965 2018-10-14 20:05
浏览 17

从切片中删除项目

I was having some issues with Golang slices.

I understand that a slice is a pointer to an underlying array, but some of the behaviour feels a little odd.

I was trying to remove an item from a slice I managed to do it by copying the slice is there a better way?

In the code below the original slice is changed.

package main

import (
    "fmt"
)

func main() {
    mySlice := []int{1,2,3,4,5,6}
    pos := 3

    slicePart1 := mySlice[:pos+1]
    slicePart2 := mySlice[pos+2:]

    fmt.Println(mySlice)
    fmt.Println(slicePart1)
    fmt.Println(slicePart2)
    new := append(slicePart1,slicePart2...)
    fmt.Println(new)
    fmt.Println(mySlice)
}
  • 写回答

1条回答 默认 最新

  • drkjzk3359 2018-10-14 20:16
    关注

    For example,

    package main
    
    import "fmt"
    
    func main() {
        s := []int{1, 2, 3, 4, 5, 6}
        fmt.Println(s)
        i := 3
        fmt.Println(i)
        s = append(s[:i], s[i+1:]...)
        fmt.Println(s)
    }
    

    Playground: https://play.golang.org/p/SVQEUE7Rrei

    Output:

    [1 2 3 4 5 6]
    3
    [1 2 3 5 6]
    

    Or, if order is not important,

    package main
    
    import "fmt"
    
    func main() {
        s := []int{1, 2, 3, 4, 5, 6}
        fmt.Println(s)
        i := 3
        fmt.Println(i)
        s[i] = s[len(s)-1]
        s = s[:len(s)-1]
        fmt.Println(s)
    }
    

    Playground: https://play.golang.org/p/lVgKew3ZJNF

    Output:

    [1 2 3 4 5 6]
    3
    [1 2 3 6 5]
    

    For several other ways, see SliceTricks.

    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序