Removing a string from a slice in Go [duplicate]

2019-02-19 08:14发布

问题:

This question already has an answer here:

  • Delete element in a slice 6 answers

I have a slice of strings, and I want to remove a specific one.

strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")

Now how can I remove the string "two" from strings?

回答1:

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]


回答2:

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



标签: string go slice