两种 go 实现 set 的思路, 分别是 map 和 bitset。

map 的 key 肯定是唯一的,而这恰好与 set 的特性一致,天然保证 set 中成员的唯一性。而且通过 map 实现 set,在检查是否存在某个元素时可直接使用 _, ok := m[key] 的语法,效率高。

原文链接:https://studygolang.com/articles/27476?fr=sidebar

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

demo

package main

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

运行结果:

s1 contains :  true
s1 contains : false
s1 contains poloxue: true
s1 contains : false
Set{, , , poloxue, , }

Examples but not exhaustive:

requiredClasses := mapset.NewSet()
requiredClasses.Add("Cooking")
requiredClasses.Add("English")
requiredClasses.Add("Math")
requiredClasses.Add("Biology") scienceSlice := []interface{}{"Biology", "Chemistry"}
scienceClasses := mapset.NewSetFromSlice(scienceSlice) electiveClasses := mapset.NewSet()
electiveClasses.Add("Welding")
electiveClasses.Add("Music")
electiveClasses.Add("Automotive") bonusClasses := mapset.NewSet()
bonusClasses.Add("Go Programming")
bonusClasses.Add("Python Programming") //Show me all the available classes I can take
allClasses := requiredClasses.Union(scienceClasses).Union(electiveClasses).Union(bonusClasses)
fmt.Println(allClasses) //Set{Cooking, English, Math, Chemistry, Welding, Biology, Music, Automotive, Go Programming, Python Programming} //Is cooking considered a science class?
fmt.Println(scienceClasses.Contains("Cooking")) //false //Show me all classes that are not science classes, since I hate science.
fmt.Println(allClasses.Difference(scienceClasses)) //Set{Music, Automotive, Go Programming, Python Programming, Cooking, English, Math, Welding} //Which science classes are also required classes?
fmt.Println(scienceClasses.Intersect(requiredClasses)) //Set{Biology} //How many bonus classes do you offer?
fmt.Println(bonusClasses.Cardinality()) //2 //Do you have the following classes? Welding, Automotive and English?
fmt.Println(allClasses.IsSuperset(mapset.NewSetFromSlice([]interface{}{"Welding", "Automotive", "English"}))) //true

Golang中使用set的更多相关文章

  1. golang中的race检测

    golang中的race检测 由于golang中的go是非常方便的,加上函数又非常容易隐藏go. 所以很多时候,当我们写出一个程序的时候,我们并不知道这个程序在并发情况下会不会出现什么问题. 所以在本 ...

  2. 基础知识 - Golang 中的正则表达式

    ------------------------------------------------------------ Golang中的正则表达式 ------------------------- ...

  3. golang中的reflect包用法

    最近在写一个自动生成api文档的功能,用到了reflect包来给结构体赋值,给空数组新增一个元素,这样只要定义一个input结构体和一个output的结构体,并填写一些相关tag信息,就能使用程序来生 ...

  4. Golang中的坑二

    Golang中的坑二 for ...range 最近两周用Golang做项目,编写web服务,两周时间写了大概五千行代码(业务代码加单元测试用例代码).用Go的感觉很爽,编码效率高,运行效率也不错,用 ...

  5. Golang 中的坑 一

    Golang 中的坑 短变量声明  Short variable declarations 考虑如下代码: package main import ( "errors" " ...

  6. google的grpc在golang中的使用

    GRPC是google开源的一个高性能.跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x. 前面写过一篇golang标准库的rpc包的用法,这篇文章接着讲一 ...

  7. Golang中Struct与DB中表字段通过反射自动映射 - sqlmapper

    Golang中操作数据库已经有现成的库"database/sql"可以用,但是"database/sql"只提供了最基础的操作接口: 对数据库中一张表的增删改查 ...

  8. Golang中WaitGroup使用的一点坑

    Golang中WaitGroup使用的一点坑 Golang 中的 WaitGroup 一直是同步 goroutine 的推荐实践.自己用了两年多也没遇到过什么问题.直到一天午睡后,同事扔过来一段奇怪的 ...

  9. Golang中使用lua进行扩展

    前言 最近在项目中需要使用lua进行扩展,发现github上有一个用golang编写的lua虚拟机,名字叫做gopher-lua.使用后发现还不错,借此分享给大家. 数据类型 lua中的数据类型与go ...

  10. golang中Context的使用场景

    golang中Context的使用场景 context在Go1.7之后就进入标准库中了.它主要的用处如果用一句话来说,是在于控制goroutine的生命周期.当一个计算任务被goroutine承接了之 ...

随机推荐

  1. 前端学习(六):body标签(四)

    进击のpython ***** 前端学习--body标签 关于前面的都是大部分的标签内容 但是就像衣服一样,除了要有,还要放到适当的位置 我们先来看看一下网页的布局: 就可以看出来,网页都是一块一块的 ...

  2. JPA第二天

    学于黑马和传智播客联合做的教学项目 感谢 黑马官网 传智播客官网 微信搜索"艺术行者",关注并回复关键词"springdata"获取视频和教程资料! b站在线视 ...

  3. 最基本的Tkinter界面操作

    1.创建应用程序主窗口对象 root = Tk() 2.在主窗口中,添加各种可视化组件 btn1 = Button(root) btn1["text"] = "点我&qu ...

  4. PHP array_udiff_uassoc() 函数

    实例 比较两个数组的键名和键值(使用用户自定义函数进行比较),并返回差集: <?phpfunction myfunction_key($a,$b){if ($a===$b){return 0;} ...

  5. PHP shuffle() 函数

    实例 把数组中的元素按随机顺序重新排列: <?php$my_array = array("red","green","blue",&q ...

  6. PDO::quote

    PDO::quote — 为SQL语句中的字符串添加引号.(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1) 说明 语法 public string PDO::quot ...

  7. luogu4443 coci 2017 Dajave

    题目 给出一个长度为2^M的排列,元素分别是0, 1, 2, ... , 2^M -1. 选择其中某个非空连续子序列,然后允许交换这个排列中某两个不同的数,然后使得这个连续子序列的所有数的按位异或(b ...

  8. IEnumerable<T>转DataTable,为空怎么办?

    public static class DataConvertor { public static DataTable ToDataTable<T>(IEnumerable<T> ...

  9. vue_shop(基于vue电商管理后台网站)

    vue_shop 目录 vue_shop day01 实现登录功能 项目预开发处理 Login.vue完整代码: 处理步骤: 添加element-ui的表单组件 添加第三方字体: 添加表单验证 导入a ...

  10. JsLint undeclared ‘window’

    如果使用IDEA 设置一下 globals 或 /*global window */ ... your script goes here https://stackoverflow.com/quest ...