View Category
Define an empty map
go
m := make(map[int]string)
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
go
m := map[string]int{ "circle": 1, "square": 4, "triangle": 2 }
Check if a key exists in a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
go
fmt.Println(pets["joe"])
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
go
pets["rob"] = "dog"
Remove an entry from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
go
fmt.Println(pets["bill"])
delete(pets, "bill")
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false
pets["bill"] = "", false
Create a histogram map from a list
Given the list
[a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
go
var maplist = make(map[string]int)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)
Categorise a list
Given the list
[one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
