Structs in Go
Learn how structs work in Go.
If you’ve ever used Python or JavaScript, you probably have experience working with the key-value object known as a dictionary. They are a versatile way to store data and provide fast lookups with values that can retrieve information in a variety of formats. The Go programming language has similar data structure called maps.
In this post, we explore maps in Go and how to create and use them.
Maps are an unordered group of key-value elements. All the keys must have the same type, and all of the values must also be of the same type.
In the example below, a map texts
is created to store abbreviations of phrases used in texting. The map uses a string data type as the key and the value is also a string data type.
package main
import "fmt"
func main() {
texts := make(map[string]string)
texts["ROFL"] = "Rolling on the floor laughing"
texts["TMI"] = "Too much information"
texts["NVM"] = "Never mind"
texts["TL;DR"] = "Too long, didn’t read"
// print single value
fmt.Println(texts["ROFL"])
fmt.Println()
// print all values
for key, value := range texts {
fmt.Println(key, ":", value)
}
}
And the output is:
Rolling on the floor laughing
ROFL : Rolling on the floor laughing
TMI : Too much information
NVM : Never mind
TL;DR : Too long, didn’t read
There is also a shorthand declaration method way to create maps using the format map[key_type]value_type{}
.
The example below creates a data
map that uses integers as the keys and strings as the values.
package main
import "fmt"
func main() {
data := map[int]string{}
data[1] = "one"
data[2] = "two"
fmt.Println(data[1])
}
The output is:
one
Removing elements can be done with the delete()
function.
In the example below, we delete the value with the key 1
.
package main
import "fmt"
func main() {
data := map[int]string{}
data[1] = "one"
data[2] = "two"
data[3] = "three"
delete(data, 1)
fmt.Println(data)
}
And the output is:
map[2:two 3:three]
We can check whether a key exists by using an if-statement.
In the example below, we create a map and a set of key values. Then we create an if-statement and make a reference to the map and the specified key, which returns a key and value if they exist. We throw away the key with the _
symbol and keep the value, which is set to the ok
variable. If the ok
value exists, the if-statement evaluates to true.
package main
import "fmt"
func main() {
data := map[int]string{}
data[1] = "one"
data[2] = "two"
data[3] = "three"
if _, ok := data[3]; ok {
fmt.Println("The key exists")
} else {
fmt.Println("The key does NOT exist")
}
}
The output is:
The key exists
In this post, we explored maps in Go and how they can be used to store data as key-value pairs.
Visit the Go page to see what other lessons there are in Go programming.