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条)

报告相同问题?

悬赏问题

  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码