Home > other >  How to implement remove range on string array golang?
How to implement remove range on string array golang?

Time:01-31

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
}

CodePudding user response:

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"}
fmt.Println(s)
s = removeRange(s, 1, 2)
fmt.Println(s)

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.

CodePudding user response:

You don't need a method or function for this at all in golang. Go slices can be subsliced and appended in place, which is how you can quickly and easily remove subsets from any slice.

Say you want to remove 2 elements, starting at index 2, you'd simply write:

Sub := append(original [:2], original [4:]...)

Demo

How this works:

  • original[:2] creates a sub-slice starting at 0, with a length of 2 elements (so index 0 and 1)
  • append because to this first part, we want to add the rest of the slice, minus the range we want to skip/remove
  • original[4:] creates another sub-slice, this time starting at index 4, and ending wherever original ends. Just like we don't explicitly mention 0 as the starting point in the first sub-slice, by not specifying a number of elements here, golang will just include all of the remaining elements in the slice.
  • ... because append is a variadic function (built-in, but you get the point), we need to pass in every element we want to append as a new argument. The ... operator expands the sub-slice and passes in every element as a separate argument.

Because we assigned the new slice to a new variable, original will remain unchanged, so if you want to overwrite the slice, you just assign it to the same variable.


Note I wrote this on my phone, so markup and code may not be quite right, but this should answer your question at least

CodePudding user response:

I've explained the code using // comments and if not commented, code is self explanatory.

package main

import (
    "fmt"
    "os"
)

func RemoveRange(s []string, index, count int) []string {
    sLen := len(s)

    // Similar semantics to match (similar) the behavior of
    // C# implementation
    switch {
    case index < 0, count < 0: // arguments are not valid
        fmt.Fprintln(os.Stderr, "error: argument out of range error")
        return s
    case index count-1 >= sLen: // range results in exceeding the limit
        fmt.Fprintln(os.Stderr, "error: argument error")
        return s
    }

    // Create a slice p and pre-allocate the size required
    // to store the resultant slice after removing range.
    // Result := s[:] -> s[:index]   s[index count:]
    // Remove := s[index:index count-1]
    p := make([]string, 0, sLen-count)
    p = append(p, s[:index]...)
    p = append(p, s[index count:]...)

    return p
}

func main() {
    s := []string{"0", "1", "2", "3", "4", "5"}
    fmt.Println(s)
    r := RemoveRange(s, 1, 3)
    fmt.Println(r)
}

Output:

[0 1 2 3 4 5]
[0 4 5]
  •  Tags:  
  • Related