栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go语言有set集合吗

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go语言有set集合吗

go语言没有set集合。Set是一个集合,set里的元素不能重复;golang的标准库中没有对set的操作,但有两种实现方法:1、使用map实现,map中的key为唯一值,这与set的特性一致;2、使用golang-set包实现。

本教程操作环境:windows10系统、GO 1.11.2、Dell G3电脑。

Go中是不提供Set类型,Set是一个集合,set里的元素不能重复。但可以使用两种方法set集合:

map

golang-set

使用map实现

在Golang中通常使用map来实现set,map中的key为唯一值,这与set的特性一致。

简单实现,如下:

set := make(map[string]bool) // New empty setset["Foo"] = true            // Addfor k := range set {         // Loop    fmt.Println(k)}delete(set, "Foo")    // Deletesize := len(set)      // Sizeexists := set["Foo"]  // Membership

map的value值是布尔型,这会导致set多占用内存空间,解决这个问题,则可以将其替换为空结构。在Go中,空结构通常不使用任何内存。

unsafe.Sizeof(struct{}{}) // 结果为 0

优化后,如下:

type void struct{}var member voidset := make(map[string]void) // New empty setset["Foo"] = member          // Addfor k := range set {         // Loop    fmt.Println(k)}delete(set, "Foo")      // Deletesize := len(set)        // Size_, exists := set["Foo"] // Membership

golang-set

golang-set-A simple set type for the Go language. Also used by Docker, 1Password, Ethereum.

在github上已经有了一个成熟的包,名为golang-set,包中提供了线程安全和非线程安全的set。提供了五个set函数:

// NewSet创建并返回空集的引用,结果集上的操作是线程安全的func NewSet(s ...interface{}) Set {}// NewSetFromSlice从现有切片创建并返回集合的引用,结果集上的操作是线程安全的func NewSetFromSlice(s []interface{}) Set {}// NewSetWith创建并返回具有给定元素的新集合,结果集上的操作是线程安全的func NewSetWith(elts ...interface{}) Set {}// NewThreadUnsafeSet创建并返回对空集的引用,结果集上的操作是非线程安全的func NewThreadUnsafeSet() Set {}// NewThreadUnsafeSetFromSlice创建并返回对现有切片中集合的引用,结果集上的操作是非线程安全的。func NewThreadUnsafeSetFromSlice(s []interface{}) Set {}

简单案例,如下:

package mainimport (    "fmt"    "github.com/deckarep/golang-set")func main() {    // 默认创建的线程安全的,如果无需线程安全    // 可以使用 NewThreadUnsafeSet 创建,使用方法都是一样的。    s1 := mapset.NewSet(1, 2, 3, 4)    fmt.Println("s1 contains 3: ", s1.Contains(3))    fmt.Println("s1 contains 5: ", s1.Contains(5))    // interface 参数,可以传递任意类型    s1.Add("poloxue")    fmt.Println("s1 contains poloxue: ", s1.Contains("poloxue"))    s1.Remove(3)    fmt.Println("s1 contains 3: ", s1.Contains(3))    s2 := mapset.NewSet(1, 3, 4, 5)    // 并集    fmt.Println(s1.Union(s2))}

结果为:

s1 contains 3:  trues1 contains 5:  falses1 contains poloxue:  trues1 contains 3:  falseSet{1, 2, 4, poloxue, 3, 5}

推荐学习:Golang教程

以上就是go语言有set集合吗的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/793778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号