Use map as a set

suggest change

Some languages have built-in types for sets.

In Go a best practice is to use a map of a desired type with values of type struct{} because a map with values of empty struct is especially optimized.

For example, a set of strings:

set := NewStringSet("hi", "hello")
fmt.Printf("Original set: %#v\n", set.Strings())

set.Delete("hi")
fmt.Printf("After delete: %#v\n", set.Strings())

set.Add("hey")
fmt.Printf("After add   : %#v\n", set.Strings())

printExists(set, "hello")
printExists(set, "ola")
Original set: []string{"hi", "hello"}
After delete: []string{"hello"}
After add   : []string{"hello", "hey"}
'hello' exists in set
'ola' doesn't exist in set

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents