dongyan4157 2019-04-12 17:36
浏览 3
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • duan0530 2019-04-12 17:48
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题