How to implement remove range on string array golang?


How can I implement RemoveRange method in golang? It is a method in C# as shown here

I want to implement RemoveRange method on my hashCode string array and return new modified array back if possible with those ranges remove.

func removeRange(hashCode []string, idx int, count int) []string {
    var temp []string
    for i, s := range hashCode {
            fmt.Println(i, s)
      // confuse here on what to do

    return temp


Simply slice the slice up until idx, skip count elements and append the rest to the result of the first slicing:

func removeRange(hashCode []string, idx int, count int) []string {
    return append(hashCode[:idx], hashCode[idx+count:]...)

Testing it:

s := []string{"0", "1", "2", "3", "4", "5"}
s = removeRange(s, 1, 2)

Which outputs (try it on the Go Playground):

[0 1 2 3 4 5]
[0 3 4 5]

Note: the above implementation does not check whether indices are valid (whether they are in range). If not, the code could panic. Add necessary checks if you need to.

Note #2: the above implementation modifies the elements of the passed slice, the returned slice will share the backing array of the parameter. If you want to avoid this, if you want to leave the input intact and allocate a new slice for the result, then do so:

func removeRange(hashCode []string, idx int, count int) []string {
    result := make([]string, 0, len(hashCode)-count)
    result = append(result, hashCode[:idx]...)
    result = append(result, hashCode[idx+count:]...)
    return result

Try this one on the Go Playground.

Answered By – icza

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.