attended := map[string]bool{
"Ann": true,
"Joe": true,
...
}
if attended[person] { // will be false if person is not in the map
fmt.Println(person, "was at the meeting")
}
I think map[string]struct{} takes no storage for the value and is the most efficient way to do this.
- Randy
> On Apr 27, 2020, at 7:20 PM, Shishir Verma <shish...@gmail.com> wrote:
>
> I think the idiomatic way to implement a set in golang is to use a map with bool values. Here is an example from effective go documentation:
>
>
> attended := map[string]bool{
> "Ann": true,
> "Joe": true,
> ...
> }
>
> if attended[person] { // will be false if person is not in the map
> fmt.Println(person, "was at the meeting")
> }
>
>
>
> On Monday, 27 April 2020 22:16:20 UTC+5:30, adithya...@gmail.com wrote:
> Basically i need a slice with indexed values, so that i can check only existence.
> or a map with only keys?
> How it can be done?
>
> --
> 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 golan...@googlegroups.com.
package main
import ( "fmt" _ "net/http/pprof" "runtime" "unsafe")
const ( entries = 1000001)
func main() { printAllocs() //Empty struct takes 0 bytes in memory whereas a boolean takes 1 s := struct{}{} b := true fmt.Printf("size of empty struct: %T, %d\n", s, unsafe.Sizeof(s)) fmt.Printf("size of a boolean: %T, %d\n", b, unsafe.Sizeof(b))
printAllocs()
//Map with int keys and bool values hashset := make(map[int]bool, entries)
for index := 0; index < entries-1; index++ { hashset[index] = true }
fmt.Printf("Number of elements in map with bool values: %d \n", len(hashset)) printAllocs()
//Map with int keys and empty struct values hashmap := make(map[int]struct{}, entries)
for index := 0; index < entries-1; index++ { hashmap[index] = struct{}{} }
fmt.Printf("Number of elements in map with empty struct values: %d \n", len(hashmap)) printAllocs()}
func printAllocs() { var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("Heap size: %6d \n", m.Alloc/1e6)}
$ GODEBUG=gctrace=1 ./mapmemHeap size: 0 size of empty struct: struct {}, 0size of a boolean: bool, 1Heap size: 0 gc 1 @0.002s 1%: 0.002+0.25+0.019 ms clock, 0.009+0.11/0.045/0.37+0.079 ms cpu, 23->23->23 MB, 24 MB goal, 4 PNumber of elements in map with bool values: 1000000 Heap size: 24 gc 2 @0.129s 0%: 0.003+0.25+0.018 ms clock, 0.012+0.076/0.066/0.22+0.072 ms cpu, 44->44->21 MB, 47 MB goal, 4 PNumber of elements in map with empty struct values: 1000000 Heap size: 22 I think it is kind of intuitive that empty struct takes 0 bytes