Removing a string from a slice in Go [duplicate]

让人想犯罪 __ 提交于 2019-12-01 09:30:44

Find the element you want to remove and remove it like you would any element from any other slice.

Finding it is a linear search. Removing is one of the following slice tricks:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

Here is the complete solution (try it on the Go Playground):

s := []string{"one", "two", "three"}

// Find and remove "two"
for i, v := range s {
    if v == "two" {
        s = append(s[:i], s[i+1:]...)
        break
    }
}

fmt.Println(s) // Prints [one three]

If you want to wrap it into a function:

func remove(s []string, r string) []string {
    for i, v := range s {
        if v == r {
            return append(s[:i], s[i+1:]...)
        }
    }
    return s
}

Using it:

s := []string{"one", "two", "three"}
s = remove(s, "two")
fmt.Println(s) // Prints [one three]

Here is a function to remove the element at a particular index:

package main

import "fmt"
import "errors"

func main() {
    strings := []string{}
    strings = append(strings, "one")
    strings = append(strings, "two")
    strings = append(strings, "three")
    strings, err := remove(strings, 1)
    if err != nil {
        fmt.Println("Something went wrong : ", err)
    } else {
        fmt.Println(strings)
    }

}

func remove(s []string, index int) ([]string, error) {
    if index >= len(s) {
        return nil, errors.New("Out of Range Error")
    }
    return append(s[:index], s[index+1:]...), nil
}

Try it on Go Playground

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!