dtp0760 2018-09-11 21:22
浏览 33
已采纳

删除切片中的元素,然后返回删除的元素和剩余的元素

I just want a function that having a slice of a struct type "t", returns the returns the element I'm looking for and the remaining, I tried with the partial solution for my problem like pointed out here: Delete element in a slice But for a weird reason, it does not work as expected https://play.golang.org/p/tvJwkF5c_tj

    func main() {
    var names = []string{"john", "julio", "pepito","carlos"}
    fmt.Println(getMe("john", names))
}
func getMe(me string, names []string) (string, []string, bool) {
    for i := range names {
        if names[i] == me {
            return names[i], append(names[:i], names[i+1:]...), true
        }
    }
    return "", nil, false
}

but the result gives me:

julio [julio pepito carlos] true

UPDATE: https://play.golang.org/p/1xbu01rOiMg Taking the answer from @Ullaakut If I do: append(names[:i], names[i+1:]...), it changes the original slice, so this does not work for me, I do not want my slice to change, because I will be using it later on

  • 写回答

1条回答 默认 最新

  • drvvvuyia15070493 2018-09-11 21:31
    关注

    Simply use the range to get both the value and the index, instead of accessing the value by using the index.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var names = []string{"john", "julio", "pepito", "carlos"}
        name, newNames, _ := getMe("john", names)
    
        fmt.Println("extracted name:\t\t\t\t", name)
        fmt.Println("new slice without extracted name:\t", newNames)
        fmt.Println("old slice still intact:\t\t\t", names)
    }
    
    func getMe(me string, names []string) (string, []string, bool) {
        var newSlice []string
    
        for i := 0; i < len(names); i++ {
            if names[i] == me {
                newSlice = append(newSlice, names[:i]...)
                newSlice = append(newSlice, names[i+1:]...)
                return names[i], newSlice, true
            }
        }
    
        return "", nil, false
    }
    

    Outputs

    extracted name:                        john
    new slice without extracted name:      [julio pepito carlos]
    old slice still intact:                [john julio pepito carlos]
    

    See playground example

    Edit after request for a faster version: Using the manual for instead of the range loop is much faster. Since you need to create a new slice without the element, it's necessary to build a new slice within the function, which is always going to take some processing power.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?