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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化