Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map[T]struct{} and map[T]bool in golang

Tags:

go

What's the difference? Is map[T]bool optimized to map[T]struct{}? Which is the best practice in Go?

Perhaps the best reason to use map[T]struct{} is that you don't have to answer the question "what does it mean if the value is false"?

like image 617
timestee Avatar asked May 19 '16 10:05

timestee


People also ask

Is struct a map Golang?

A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type. Iterating over a map: You can also run a loop to access and operate each map key individually. If a key-value pair already exists in the map it will just update the old pair with the new.

What are maps in Golang?

In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.

What does a map return Golang?

Maps in Go will return the zero value for the value type of the map when the requested key is missing. Because of this, you need an alternative way to differentiate a stored zero, versus a missing key.

Are maps mutable in Golang?

No. Maps are reference by default.


2 Answers

From "The Go Programming Language":

The struct type with no fields is called the empty struct, written struct{}. It has size zero and carries no information but may be useful nonetheless. Some Go programmers use it instead of bool as the value type of a map that represents a set, to emphasize that only the keys are significant, but the space saving is marginal and the syntax more cumbersome, so we generally avoid it.

If you use bool testing for presence in the "set" is slightly nicer since you can just say:

if mySet["something"] {
    /* .. */
}
like image 96
cnicutar Avatar answered Sep 29 '22 08:09

cnicutar


Difference is in memory requirements. Under the bonnet empty struct is not a pointer but a special value to save memory.

like image 37
Eugene Lisitsky Avatar answered Sep 29 '22 08:09

Eugene Lisitsky