Golang maps can be tricky. Understanding how they work can help you improve the performance of your code
Recently, I found an interesting question on Stack Overflow. It is related to memory allocation in Golang maps when we use an interface as the value (map[int]interface{}
)_ vs. _an empty struct as the value(map[int]struct{}
). The OP set up two benchmark tests to compare the two map types and found some weird results. The benchmarks are described as follows:
In the code below, we have a function for each map type. Each function basically creates a map and then repeats a zero value assignment a fixed number of times. That is, by the end of the execution, the map will have a fixed number of entries and each entry will receive the zero value of the type(nil
for interfaces and struct{}{}
for empty structs).
package main
func main() {}
func MapWithInterface() {
m := map[int]interface{}{}
for i := 1; i <= 100; i++ {
m[i] = nil
}
}
func MapWithEmptyStruct() {
m := map[int]struct{}{}
for i := 1; i <= 100; i++ {
m[i] = struct{}{}
}
}
Benchmarks:
package main
import "testing"
func Benchmark_Interface(b *testing.B) {
for i := 0; i < b.N; i++ {
MapWithInterface()
}
}
func Benchmark_EmptyStruct(b *testing.B) {
for i := 0; i < b.N; i++ {
MapWithEmptyStruct()
}
}
Maps (also called dictionaries) are a very useful tool in helping to store and organize objects to be accessed in an efficient method. Most basic implementations of a map involve using a key to access a value in the map, resulting in key-value pairs, in which one key is associated with a specific value in the map. Within Go, maps follow this definition. This blog will cover the basic use cases of maps in Go, and how a newcomer to the language may utilize them for their applications. Explore and learn about the usage of maps in Go. Working with Golang Maps
Golang Structs Example | Structs In Go Explained. Go struct is a user-defined type which represents a collection of fields.
Golang map is an inbuilt data type that has keys that are unique within the map while the values may or may not be the same.
Maps.me 2.0 has both online and offline maps while offering DeFi functionalities to its 100M+ users. Powering Maps.me 2.0 is the MAPS token which may provide token holders with 100% of the platform’s net revenues. Token-holders using the app will also benefit from personalized promotions and rewards, likely driving adoption, retention, and virality of MAPS within the community. There are very few apps with a user base as large as ours, so Maps.me is positioned to quickly put DeFi financial services in the hands of many.
Go is not a pure object oriented programming language. It does not provide classes, but it does provide structs. Struct Field Tags in Golang