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

编程入门 行业动态 更新时间:2024-10-27 16:33:51
本文介绍了我如何创建一个包含唯一字符串的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想创建一个包含唯一字符串的数组。

var paths = make([] string,0) func main(){ //动态添加成员 paths = append(paths,aaa) paths = append(paths,bbb) paths = append(路径,bbb) paths =追加(路径,ccc) //转换[aaa,bbb,bbb,ccc] - > ; [aaa,bbb,ccc] //或者我可以使用某些不允许使用相同字符串automaticaly的类吗?

解决方案

独特元素,即设置数据类型。 Go没有设置数据类型,但可以使用 map [string] bool 作为一个集合。

因此,您可以将元素添加到 map [string] bool 中,作为 true的键作为值:

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

要检查一个元素是否已经在集合(map)中,您可以简单地使用 index expression :

exists:= m [somevalue]

这个漏洞利用了零值,也就是说,如果map还没有包含元素,则返回值类型的零值,即 false 在 bool 类型的情况下,正确表明该元素不在收藏中n。

地图中的元素没有固定顺序。如果您需要保留订单(例如广告订单),请使用切片(记住订单)和地图(以确定要添加的元素是否为新)。这对辅助程序 add()函数是最简单的:

var m = make(map [string] bool) var a = [] string {} $ b $ func main(){ add(aaa) add( bbb) add(bbb) add(ccc)} func add(s string){ if m [s] { return //已经在地图中} a = append(a,s)m [s] = true }

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? }

解决方案

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.

So 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 }

更多推荐

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

本文发布于:2023-11-30 17:59:53,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   创建一个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!