美文网首页
go 实现 set

go 实现 set

作者: wayyyy | 来源:发表于2022-03-19 02:41 被阅读0次

go 中自带的标准库只有map,而没有set,那么我们可以利用 mapstruct{} size 为0 来简单实现一个 set

package main

import "fmt"

type Set map[string]struct{}

func NewSet() Set {
    s := make(map[string]struct{})
    return Set(s)
}

func NewSetWithInitSize(size int) Set {
    s := make(map[string]struct{}, size)
    return Set(s)
}

func (s Set) Has(key string) bool {
    _, exist := s[key]
    return exist
}

func (s Set) Add(key string) {
    s[key] = struct{}{}
}

func (s Set) Delete(key string) {
    delete(s, key)
}

func main() {
    s := NewSet()

    s.Add("hello")
    s.Add("world")
    s.Add("go")

    exist := s.Has("hello")
    if exist {
        fmt.Println("exist")
    }

    exist = s.Has("world")
    if exist {
        fmt.Println("exist")
    }

    s.Delete("go")

    exist = s.Has("go")
    if exist {
        fmt.Println("exist")
    } else {
        fmt.Println("not exist")
    }
}

更加完备的set,使用开源库:golang-set

相关文章

  • go 实现 set

    go 中自带的标准库只有map,而没有set,那么我们可以利用 map 和 struct{} size 为0 来简...

  • Go学习笔记四(Map扩展)

    Map 与⼯厂模式 Map 的 value 可以是一个⽅法 实现Set Go 的内置集合中没有 Set 实现, 可...

  • golang练手小项目系列(6)-使用map实现set

    问题描述 go没有提供set数据结构,请用map实现set 要点 需要支持方法: Add 添加元素 Remove ...

  • Go 通过 map 实现 set

    众所周知,Golang 自带的数据结构是没有set集合的。 那么,今天我们通过map来实现一个不重复的set集合。...

  • Golang实现并查集

    模拟C++实现了一个并查集,主要是理解连通图的原理。main.go utils/union_find_set.go...

  • flutter 一些记录

    Constraints go down. Sizes go up. Positions are set by pa...

  • 让go get 哗哗的下载

    go get 使用代理 查看go的环境变量 go env 设置代理 set GOPROXY=https://gop...

  • ...new Set([])

    new Set实现去重 ...实现解构 let set =new Set(['a','b','c','a']); ...

  • 2018-12-31 2019

    If you set goals and go after them with all the determina...

  • 24.依赖管理及go module

    Go语言的依赖管理随着版本的更迭正逐渐完善起来。 windows开启go module:set GO111MODU...

网友评论

      本文标题:go 实现 set

      本文链接:https://www.haomeiwen.com/subject/kbcgdrtx.html