本文摘自php中文网,作者青灯夜游,侵删。
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中通常使用map来实现set,map中的key为唯一值,这与set的特性一致。
简单实现,如下:
1 2 3 4 5 6 7 8 | set := make(map[string]bool)
set[ "Foo" ] = true
for k := range set {
fmt.Println(k)
}
delete (set, "Foo" )
size := len(set)
exists := set[ "Foo" ]
|
map的value值是布尔型,这会导致set多占用内存空间,解决这个问题,则可以将其替换为空结构。在Go中,空结构通常不使用任何内存。
1 | unsafe.Sizeof(struct{}{})
|
优化后,如下:
1 2 3 4 5 6 7 8 9 10 11 | type void struct{}
var member void
set := make(map[string]void)
set[ "Foo" ] = member
for k := range set {
fmt.Println(k)
}
delete (set, "Foo" )
size := len(set)
_, exists := set[ "Foo" ]
|
golang-set
golang-set-A simple set type for the Go language. Also used by Docker, 1Password, Ethereum.
在github上已经有了一个成熟的包,名为golang-set,包中提供了线程安全和非线程安全的set。提供了五个set函数:
1 2 3 4 5 6 7 8 9 10 | func NewSet(s ...interface{}) Set {}
func NewSetFromSlice(s []interface{}) Set {}
func NewSetWith(elts ...interface{}) Set {}
func NewThreadUnsafeSet() Set {}
func NewThreadUnsafeSetFromSlice(s []interface{}) Set {}
|
简单案例,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package main
import (
"fmt"
"github.com/deckarep/golang-set"
)
func main() {
s1 := mapset.NewSet(1, 2, 3, 4)
fmt.Println( "s1 contains 3: " , s1.Contains(3))
fmt.Println( "s1 contains 5: " , s1.Contains(5))
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))
}
|
结果为:
1 2 3 4 5 | s1 contains 3: true
s1 contains 5: false
s1 contains poloxue: true
s1 contains 3: false
Set{1, 2, 4, poloxue, 3, 5}
|
推荐学习:Golang教程
以上就是go语言有set集合吗的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Go语言是面向对象的吗
go 语言结构
Go语言用什么开发工具?
Go语言主要是用来做什么的
Go语言结构体
Go语言package是什么
Go语言函数方法
Go语言中控制并发数量的方法
Go语言有什么特点?
Go语言 goto 语句
更多相关阅读请进入《Go语言》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » go语言有set集合吗