0
0
Goprogramming~5 mins

Map creation in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a map in Go?
A map in Go is a collection that stores key-value pairs. It allows you to look up a value by its key quickly, like a dictionary or a phone book.
Click to reveal answer
beginner
How do you declare an empty map in Go?
You declare an empty map using the syntax: var m map[string]int or by using make: m := make(map[string]int). The second way creates an initialized map ready to use.
Click to reveal answer
beginner
How do you add or update a key-value pair in a Go map?
You add or update a value by assigning it to a key: m["key"] = value. If the key exists, the value updates; if not, it adds a new pair.
Click to reveal answer
intermediate
What happens if you try to read a key that does not exist in a Go map?
Reading a non-existent key returns the zero value for the map's value type. For example, if the value type is int, it returns 0. You can also check if the key exists using the two-value assignment.
Click to reveal answer
intermediate
How do you check if a key exists in a Go map?
Use the two-value assignment: value, ok := m["key"]. The variable ok is true if the key exists, false otherwise.
Click to reveal answer
How do you create an empty map of string keys and int values in Go?
AAll of the above
Bm := map[string]int{}
Cvar m map[string]int
Dm := make(map[string]int)
What is the zero value returned when accessing a missing key in a map of type map[string]int?
A"" (empty string)
Bnil
C0
Dfalse
Which syntax checks if a key exists in a Go map?
Avalue := m["key"]
Bexists := m.contains("key")
Cif m.hasKey("key")
Dvalue, ok := m["key"]
What happens if you assign a value to a key in a nil map?
AIt causes a runtime panic
BThe map automatically initializes
CThe assignment is ignored
DThe key is added but value is zero
How do you declare and initialize a map with some key-value pairs in one line?
Am := make(map[string]int){"a": 1, "b": 2}
Bm := map[string]int{"a": 1, "b": 2}
Cvar m = map[string]int{}
Dm := new(map[string]int)
Explain how to create, add, and check keys in a Go map.
Think about how you start a map, put things in it, and see if something is there.
You got /4 concepts.
    Describe what happens when you read a key that does not exist in a Go map and how to handle it.
    Remember the difference between missing keys and keys with zero values.
    You got /3 concepts.