• This repository has been archived on 03/Aug/2018
  • Stars
    star
    657
  • Rank 68,589 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 11 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Set data structure for Go

Archived project. No maintenance.

This project is not maintained anymore and is archived.. Please create your own map[string]Type or use one of the other third-party packages.

Thanks all for their work on this project.

Set GoDoc Build Status

Set is a basic and simple, hash-based, Set data structure implementation in Go (Golang).

Set provides both threadsafe and non-threadsafe implementations of a generic set data structure. The thread safety encompasses all operations on one set. Operations on multiple sets are consistent in that the elements of each set used was valid at exactly one point in time between the start and the end of the operation. Because it's thread safe, you can use it concurrently with your goroutines.

For usage see examples below or click on the godoc badge.

Install and Usage

Install the package with:

go get github.com/fatih/set

Import it with:

import "githug.com/fatih/set"

and use set as the package name inside the code.

Examples

Initialization of a new Set

// create a set with zero items
s := set.New(set.ThreadSafe) // thread safe version
s := set.New(set.NonThreadSafe) // non thread-safe version

Basic Operations

// add items
s.Add("istanbul")
s.Add("istanbul") // nothing happens if you add duplicate item

// add multiple items
s.Add("ankara", "san francisco", 3.14)

// remove item
s.Remove("frankfurt")
s.Remove("frankfurt") // nothing happens if you remove a nonexisting item

// remove multiple items
s.Remove("barcelona", 3.14, "ankara")

// removes an arbitary item and return it
item := s.Pop()

// create a new copy
other := s.Copy()

// remove all items
s.Clear()

// number of items in the set
len := s.Size()

// return a list of items
items := s.List()

// string representation of set
fmt.Printf("set is %s", s.String())

Check Operations

// check for set emptiness, returns true if set is empty
s.IsEmpty()

// check for a single item exist
s.Has("istanbul")

// ... or for multiple items. This will return true if all of the items exist.
s.Has("istanbul", "san francisco", 3.14)

// create two sets for the following checks...
s := s.New("1", "2", "3", "4", "5")
t := s.New("1", "2", "3")

// check if they are the same
if !s.IsEqual(t) {
    fmt.Println("s is not equal to t")
}

// if s contains all elements of t
if s.IsSubset(t) {
	fmt.Println("t is a subset of s")
}

// ... or if s is a superset of t
if t.IsSuperset(s) {
	fmt.Println("s is a superset of t")
}

Set Operations

// let us initialize two sets with some values
a := set.New(set.ThreadSafe)
a := set.Add("ankara", "berlin", "san francisco")
b := set.New(set.NonThreadSafe)
b := set.Add("frankfurt", "berlin")

// creates a new set with the items in a and b combined.
// [frankfurt, berlin, ankara, san francisco]
c := set.Union(a, b)

// contains items which is in both a and b
// [berlin]
c := set.Intersection(a, b)

// contains items which are in a but not in b
// [ankara, san francisco]
c := set.Difference(a, b)

// contains items which are in one of either, but not in both.
// [frankfurt, ankara, san francisco]
c := set.SymmetricDifference(a, b)
// like Union but saves the result back into a.
a.Merge(b)

// removes the set items which are in b from a and saves the result back into a.
a.Separate(b)

Multiple Set Operations

a := set.New(set.ThreadSafe)
a := set.Add("1", "3", "4", "5")
b := set.New(set.ThreadSafe)
b := set.Add("2", "3", "4", "5")
c := set.New(set.ThreadSafe)
c := set.Add("4", "5", "6", "7")

// creates a new set with items in a, b and c
// [1 2 3 4 5 6 7]
u := set.Union(a, b, c)

// creates a new set with items in a but not in b and c
// [1]
u := set.Difference(a, b, c)

// creates a new set with items that are common to a, b and c
// [5]
u := set.Intersection(a, b, c)

Helper methods

The Slice functions below are a convenient way to extract or convert your Set data into basic data types.

// create a set of mixed types
s := set.New(set.ThreadSafe)
s := set.Add("ankara", "5", "8", "san francisco", 13, 21)

// convert s into a slice of strings (type is []string)
// [ankara 5 8 san francisco]
t := set.StringSlice(s)

// u contains a slice of ints (type is []int)
// [13, 21]
u := set.IntSlice(s)

Concurrent safe usage

Below is an example of a concurrent way that uses set. We call ten functions concurrently and wait until they are finished. It basically creates a new string for each goroutine and adds it to our set.

package main

import (
	"fmt"
	"strconv"
	"sync"

	"github.com/fatih/set"
)

func main() {
	var wg sync.WaitGroup // this is just for waiting until all goroutines finish

	// Initialize our thread safe Set
	s := set.New(set.ThreadSafe)

	// Add items concurrently (item1, item2, and so on)
	for i := 0; i < 10; i++ {
		wg.Add(1)

		go func(i int) {
			defer wg.Done()

			item := "item" + strconv.Itoa(i)
			fmt.Println("adding", item)
			s.Add(item)
		}(i)
	}

	// Wait until all concurrent calls finished and print our set
	wg.Wait()
	fmt.Println(s)
}

Credits

License

The MIT License (MIT) - see LICENSE.md for more details

More Repositories

1

vim-go

Go development plugin for Vim
Vim Script
15,577
star
2

color

Color package for Go (golang)
Go
6,536
star
3

structs

Utilities for Go structs
Go
3,811
star
4

vim-go-tutorial

Tutorial for vim-go
Vim Script
2,122
star
5

gomodifytags

Go tool to modify struct field tags
Go
1,995
star
6

pool

Connection pool for Go's net.Conn interface
Go
1,331
star
7

subvim

Vim customized to be like SublimeText
C++
1,122
star
8

dotfiles

My personal dotfiles
Lua
792
star
9

structtag

Parse and modify Go struct field tags
Go
568
star
10

errwrap

Go tool to wrap and fix errors with the new %w verb directive
Go
366
star
11

semgroup

Like errgroup/waitgroup, but only runs a maximum of tasks at any time.
Go
280
star
12

faillint

Report unwanted import path and declaration usages
Go
229
star
13

hclfmt

Format and prettify HCL files
Go
227
star
14

motion

Navigation and insight in Go
Go
180
star
15

astrewrite

Go tool to walk & rewrite AST
Go
166
star
16

camelcase

Split a camelcase word into a slice of words in Go
Go
158
star
17

starhook

Manage & Analyze repositories at scale
Go
93
star
18

vim-hclfmt

Vim plugin for hclfmt
Vim Script
73
star
19

stopwatch

Stopwatch functionality for Go
Go
69
star
20

images

Images is a tool for managing machine images from multiple providers
Go
68
star
21

addlint

An example linter written with go/analysis for tutorial purposes
Go
53
star
22

gb-example

Example gb project with dependencies and CI integration
Go
47
star
23

hcl

HCL Parser and Printer in Go
Go
44
star
24

templatectl

Simple templating CLI
Go
42
star
25

twirpdemo

An example repository of using the Twirp RPC framework with Go
Go
32
star
26

talks

My personal talk slides
Go
24
star
27

unexport

Unexport notused exported identifiers in Go
Go
22
star
28

kodla-talk-2022

Code and slides for Kodla 2022
Go
20
star
29

flags

Flag parsing in Go
Go
18
star
30

vim-nginx

Nginx runtime files for Vim
Vim Script
17
star
31

dvb-t2

Software implementation of DVB-T2
Objective-C
16
star
32

sicp

My personal notes, solutions, thoughts, etc.. about SICP
16
star
33

amqp-examples

Examples to show basic amqp commands in different languages
Go
15
star
34

testmod

Testing Go modules
AMPL
11
star
35

RailsDashboard.kdapp

An easy way to learn, test and deploy Rails
CoffeeScript
7
star
36

cafetiere

An iOS app to make beautiful Coffee
Objective-C
6
star
37

koding-wiki

Koding framework docs to build KD Apps
6
star
38

blog.arsln.org-backup

Fatih Arslan's Personal Blog
CSS
4
star
39

docker-ubuntu-go

Docker image for Go and Ubuntu
Shell
4
star
40

sinerji

A gui written in PyQt4 that uses Avahi as backend for Synergy
Python
1
star
41

snippets

Snippets, code examples, etc..
C
1
star
42

pisi-vim

A vim plugin for pisi packaging
Vim Script
1
star