Friday, April 26, 2024
HomeGolangGolang maps: declaring and initializing

Golang maps: declaring and initializing


What’s a Golang map? Why is it helpful? How does it examine to a slice? How do you declare a map? How do you initialize a map in Go? Worry not; all these questions are answered on this pleasant introduction to certainly one of Go’s strongest options.

Name ’em what you want—hashes, dictionaries, associative arrays, or, within the Go language, maps—this type of knowledge construction is acquainted to each programmer:

{
    'eggs': 1.75,
    'bacon': 3.22,
    'sausage': 1.89,
}

What’s a Golang map?

The map knowledge kind is constructed into Golang, so we regularly use it. Primarily, it lets us retailer some worth (just like the 1.75 worth within the instance above) and retrieve it by wanting up a key (like eggs).

Why is this handy? Properly, one other approach to retailer a bunch of associated knowledge values could be in a slice:

menu := []float64{1.75, 3.22, 1.89}

That is inconvenient to cope with as a result of we will solely retrieve a price by its index (0, 1, 2, 3, and so on), or by each worth, in flip, to see if it’s the one we would like. And we will’t relate the values to different issues. For instance, which of those values corresponds to the value of eggs? It’s unimaginable to know.

Against this, a map lets us take one set of issues (eggsbaconsausage), and arrange a one-to-one correspondence (a mapping) with one other set of issues (1.75, 3.22, 1.89). Way more handy once we need to search for the value of eggs, for instance.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments