Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I really like google golang but could some one explain what the rationale is for the implementors having left out a basic data structure such as sets from the standard library?

share|improve this question
5  
The language is actually called Go, not golang –  jozefg Nov 28 '12 at 2:44
18  
But "golang" is more searchable –  Matt May 29 '13 at 19:27
3  
Way more searchable. Googling "go set" returns images of a wooden board with black and white pieces. –  Doug Richardson Feb 10 at 5:55

1 Answer 1

up vote 11 down vote accepted

One potential reason for this omission is that it's really easy to model sets with a map.

To be honest I think it's a bit of an oversight too, however looking at Perl, the story's exactly the same. In Perl you get lists and hashtables, in Go you get arrays, slices, and maps. In Perl you'd generally use a hashtable for any and all problems relating to a set, the same is applicable to Go.

Example

to imitate a set ints in Go, we define a map:

set := make(map[int]bool)

To add something is as easy as:

i := valueToAdd()
set[i] = true

Deleting something is just

delete(set, i)

And the potential awkwardness of this construct is easily abstracted away:

type IntSet struct {
    set map[int]bool
}

func (set *IntSet) Add(i int) bool {
    _, found := set.set[i]
    set.set[i] = true
    return !found   //False if it existed already
}

And delete and get can be defined similarly, I have the complete implementation here . The major disatvantage here is the fact that go doesn't have generics. However it is possible to do this with interface{} in which case you'd have cast the results of get.

share|improve this answer
    
I've seen comments by Go authors suggestion that generics are a hoped-for feature, there being a hurdle in the way of needing to work out what the best idomatic pattern should be before committing to extending the language. –  Rick-777 Apr 16 '13 at 17:49
1  
Here's my slightly-revised version with Contains and Size methods: play.golang.org/p/tDdutH672- –  Rick-777 Apr 16 '13 at 18:07
1  
Instead of map[int]bool one can use map[int]struct{} instead. I prefer the last. –  pepper_chico Dec 11 '13 at 2:26
1  
map[int]struct{} .. The struct{} takes 0 bytes. –  Boopathi Rajaa Dec 13 '13 at 4:34
1  
github.com/fatih/set is an implementation of my based on maps and empty structs. It's thread safe and has a simple api. –  Fatih Arslan Jan 11 at 23:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.