如何创建包含唯一字符串的数组? [英] How can I create an array that contains unique strings?

查看: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?
}

推荐答案

如果你想要一个独特元素的集合,那就是 设置 数据类型.Go 没有集合数据类型,但您可以使用 map[string]bool 来充当集合.

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.

对于不错"的集合,使用具有 bool 值类型(具有 true 值)的映射并利用 零值.对于内存占用最小的集合,使用 struct{} 值类型的映射,因为 struct{} 类型的值不占用内存;并使用逗号确定成语来判断一个值是否在集合/映射中.

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.

这是不错"版本的 set 的样子.而不是切片将您的元素添加到 map[string]bool 作为键和 true 作为值:

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"]

这利用了零值,即如果地图尚未包含元素,返回值类型的零值,在 bool 类型的情况下为 false,正确指示该元素不在集合中.

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.

地图中的元素没有固定的顺序.如果您需要保持顺序(例如插入顺序),则使用切片(记住顺序)和映射(判断要添加的元素是否是新元素).使用辅助 add() 函数最简单:

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
}

这篇关于如何创建包含唯一字符串的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆