Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a string from a slice in Go [duplicate]

Tags:

string

slice

go

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?

like image 993
Patrick Reck Avatar asked Dec 03 '15 15:12

Patrick Reck


2 Answers

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]
like image 70
icza Avatar answered Oct 14 '22 05:10

icza


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

like image 21
Romin Avatar answered Oct 14 '22 07:10

Romin