Go does not have set by default but there is way to imitate it in Go.
The following is an example code piece to create “set” in Go by setting a map with empty values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$ cat test.go
package main
import (
"fmt"
)
// Main function
func main() {
set := make(map[string]struct{})
set["cat"] = struct{}{}
set["dog"] = struct{}{}
set["rabbit"] = struct{}{}
if _, ok := set["rabbit"]; ok {
fmt.Println("rabbit exists")
}
delete(set,"rabbit")
if _, ok := set["rabbit"]; ok {
fmt.Println("exist")
}else{
fmt.Println("rabbit doesn't exist")
}
}
$ go run test.go
rabbit exists
rabbit doesn't exist
Comments powered by Disqus.