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
"?
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.
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.
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.
No. Maps are reference by default.
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"] {
/* .. */
}
Difference is in memory requirements. Under the bonnet empty struct is not a pointer but a special value to save memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With