删除切片中的元素并返回删除的元素和剩余的元素

我只想要一个具有结构类型“t”的切片的函数,返回返回我正在寻找的元素和剩余的元素,我尝试使用部分解决方案来解决我的问题,就像这里指出的那样:Delete element in a slice 但出于一个奇怪的原因,它没有按预期工作 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

}

但结果给了我:


julio [julio pepito carlos] true

更新:https: //play.golang.org/p/1xbu01rOiMg 从@Ullaakut 那里得到答案如果我这样做:append(names[:i], names[i+1:]...),它会改变原始切片,所以这对我不起作用,我不希望我的切片改变,因为我稍后会用到它



繁星点点滴滴
浏览 85回答 1
1回答

Smart猫小萌

只需使用范围来获取值和索引,而不是使用索引来访问值。package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; var names = []string{"john", "julio", "pepito", "carlos"}&nbsp; &nbsp; name, newNames, _ := getMe("john", names)&nbsp; &nbsp; fmt.Println("extracted name:\t\t\t\t", name)&nbsp; &nbsp; fmt.Println("new slice without extracted name:\t", newNames)&nbsp; &nbsp; fmt.Println("old slice still intact:\t\t\t", names)}func getMe(me string, names []string) (string, []string, bool) {&nbsp; &nbsp; var newSlice []string&nbsp; &nbsp; for i := 0; i < len(names); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if names[i] == me {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newSlice = append(newSlice, names[:i]...)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newSlice = append(newSlice, names[i+1:]...)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return names[i], newSlice, true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return "", nil, false}产出extracted name:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; johnnew slice without extracted name:&nbsp; &nbsp; &nbsp; [julio pepito carlos]old slice still intact:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [john julio pepito carlos]参见游乐场示例在请求更快的版本后进行编辑:使用手册 for 而不是范围循环要快得多。由于您需要创建一个没有元素的新切片,因此有必要在函数内构建一个新切片,这总是需要一些处理能力。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go