

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Maps
incomplete
2: Mutations
incomplete
3: Key Types
incomplete
4: Count Instances
incomplete
5: Effective Go
incomplete
6: Nested
incomplete
7: Distinct Words
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Maps are similar to JavaScript objects, Python dictionaries, and Ruby hashes. Maps are a data structure that provides key->value mapping.
The zero value of a map is nil.
We can create a map by using the make() function:
ages := make(map[string]int)
ages["John"] = 37
ages["Mary"] = 24
ages["Mary"] = 21 // overwrites 24
Or by using a literal:
ages := map[string]int{
"John": 37,
"Mary": 21,
}
Map values can be structs too:
type car struct {
registration string
model string
}
cars := map[string]car{
"ABC-123": {registration: "ABC-123", model: "Civic"},
}
The len() function works on a map, it returns the total number of key/value pairs.
ages := map[string]int{
"John": 37,
"Mary": 21,
}
fmt.Println(len(ages)) // 2
We can speed up our contact-info lookups by using a map!
O(1)O(n)Complete the getUserMap function. It takes a slice of names and a slice of phone numbers, and returns a map of name -> user structs and an error. A user struct just contains a user's name and phone number. The first element in the names slice pairs with the first phone number, and so on.
If the length of names and phoneNumbers is not equal, return an error with the string "invalid sizes".