为切片字符串添加自定义方法[]

I'm creating a utility package for my project.

Many of my string slices need a function to 1. remove duplicates 2. remove empty strings

I know 1 way to do this:1. Add a function for each case which accepts a string slice and returns a string slice

func removeEmpty(s []string) []string {

    i := 0 // i points to next available pos

    for _, v := range s {
        if v != "" {
            s[i] = v
            i++
        }
    }

    return s[:i]
}

func dedup(s []string) []string {

    i := 0 // i points to next available pos
    mp := map[string]bool{}

    for _, v := range s {
        if _, ok := mp[v]; !ok {
            s[i] = v
            mp[v] = true
            i++
        }
    }

    return s[:i]
}

when I apply these 2 functions to my slice, I can do:

mySlice := string[]{}
mySlice = dedup(removeEmpty(mySlice))

I want to make it somthing like:

mySlice = mySlice.dedup().removeEmpty()

or

mySlice.dedup().removeEmpty()

Maybe I can add custom method to slice[] ?

I tried writing it

func (s []string) removeEmpty() {

}

I'm getting complie error.

You can't define methods on []string, but you can define your own type based on []string and define methods on that:

type myStringSlice []string

func (s myStringSlice) removeEmpty() myStringSlice {
    i := 0 // i points to next available pos

    for _, v := range s {
        if v != "" {
            s[i] = v
            i++
        }
    }

    return s[:i]
}

func (s myStringSlice) dedup() myStringSlice {

    i := 0 // i points to next available pos
    mp := map[string]bool{}

    for _, v := range s {
        if _, ok := mp[v]; !ok {
            s[i] = v
            mp[v] = true
            i++
        }
    }

    return s[:i]
}

See https://play.golang.org/p/u1z_N3c_wPP.

As mentioned in the documentation:

You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package.

So you have to declare a type on []string and then declare the method on your own type.