sets — Unordered collections of unique elements

527 views
Skip to first unread message

Игорь Авдошкин

unread,
Mar 22, 2014, 11:31:22 PM3/22/14
to golan...@googlegroups.com
Hi! 

Code python:

slice_int = [1,1,2,2,2,3,3]

slice_string = ["go", "go", "golang", "golang"]

print set(slice_int)
print set(slice_string)

Translate into Golang exists or built-in function?

Matthew Holt

unread,
Mar 22, 2014, 11:41:17 PM3/22/14
to golan...@googlegroups.com
Well, a set in Go is usually implemented as a map. Typically it's convenient for the value to be bool:

mySet := make(map[string]bool)

So to translate a slice to a map, something like this:

for _, val := range mySlice {
   mySet[val] = true
}

Should do the trick. This will not implement a "multi-set", though, so be aware that only unique elements will be admitted.

Gyepi SAM

unread,
Mar 22, 2014, 11:58:28 PM3/22/14
to Игорь Авдошкин, golan...@googlegroups.com
You can use maps to represent sets

map[int]bool
map[string]bool

If you want to print sets differently from maps, type them and implement the
Stringer interface.

type IntSet map[int]bool
type StringSet map[string]bool

func (is IntSet) String() string {...}
...

-Gyepi

Jason Del Ponte

unread,
Mar 23, 2014, 12:52:10 AM3/23/14
to golan...@googlegroups.com
Recently I've been seeing code implement a set as
map[string]struck {}

Out of curiosity, is this better than a bool, or just different?

http://play.golang.org/p/S07WunT265

Dan Kortschak

unread,
Mar 23, 2014, 1:02:42 AM3/23/14
to Jason Del Ponte, golan...@googlegroups.com
Save one byte per entry since the value is not stored, just its presence
(which in this case is enough).

Francesc Campoy Flores

unread,
Mar 23, 2014, 12:21:47 PM3/23/14
to Dan Kortschak, Jason Del Ponte, golan...@googlegroups.com
Implementing a multiset would be as easy as having map[string]int :-)


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
--

Dan Kortschak

unread,
Mar 23, 2014, 4:38:01 PM3/23/14
to Francesc Campoy Flores, Jason Del Ponte, golan...@googlegroups.com
Yes, that's ho I do it unless there are additional attributes of the members that are not keyed on, in which case it's either map[T][]M or map[T]*[]M.

Francesc Campoy Flores

unread,
Mar 23, 2014, 5:06:49 PM3/23/14
to Dan Kortschak, Jason Del Ponte, golan...@googlegroups.com
Then it's a multimap, not a multiset :-)

But yes, completely agreed.

Dan Kortschak

unread,
Mar 23, 2014, 5:16:25 PM3/23/14
to Francesc Campoy Flores, Jason Del Ponte, golan...@googlegroups.com
A rose by any other name..., or https://xkcd.com/1322/
Reply all
Reply to author
Forward
0 new messages