duandazhen7306 2015-10-19 05:27
浏览 31
已采纳

如何创建包含唯一字符串的数组?

I want to create an array that contains unique strings. How can I do that?

var paths = make([]string, 0)

func main() {
    // Members are added dynamically
    paths = append(paths, "aaa")
    paths = append(paths, "bbb")
    paths = append(paths, "bbb")
    paths = append(paths, "ccc")

    // convert ["aaa", "bbb", "bbb", "ccc"] -> ["aaa", "bbb", "ccc"] 
    // or can I use some class that disallow the same string automaticaly?
}
  • 写回答

1条回答 默认 最新

  • douzhao2047 2015-10-19 05:34
    关注

    If you want a collection of unique elements, that is the Set data type. Go does not have a set data type, but you can use a map[string]bool to act as a set.

    For a "nice" set, use a map with bool value type (with true values) and exploit the zero value. For a set with the smallest memory footprint, use a map with struct{} value type as values of struct{} type occupy no memory; and use the comma-ok idiom to tell if a value is in the set / map.

    Here's how the "nice" version of set looks like. Instead of a slice add your elements to a map[string]bool as the key with a true as the value:

    m := make(map[string]bool)
    
    m["aaa"] = true
    m["bbb"] = true
    m["bbb"] = true
    m["ccc"] = true
    

    To check if an element is already in the collection (map), you can simply use an index expression:

    exists := m["somevalue"]
    

    This exploits the zero value, that is if the map does not yet contain an element, the zero value of the value type is returned which is false in case of bool type, properly indicating that the element is not in the collection.

    Elements in a map have no fixed order. If you need to keep the order (e.g. insertion order), then use a slice (to remember the order) and a map (to tell if an element to be added is new). This is easiest with a helper add() function:

    var m = make(map[string]bool)
    var a = []string{}
    
    func main() {
        add("aaa")
        add("bbb")
        add("bbb")
        add("ccc")
    }
    
    func add(s string) {
        if m[s] {
            return // Already in the map
        }
        a = append(a, s)
        m[s] = true
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历