0
0
Goprogramming~5 mins

Adding and updating values in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you add a new key-value pair to a map in Go?
You add a new key-value pair by assigning a value to a new key like this: mapName[newKey] = newValue.
Click to reveal answer
beginner
How do you update an existing value in a Go map?
You update a value by assigning a new value to an existing key: mapName[existingKey] = newValue.
Click to reveal answer
beginner
What happens if you assign a value to a key that does not exist in a Go map?
Go will add the key to the map with the assigned value. Maps grow dynamically when you add new keys.
Click to reveal answer
intermediate
Can you add or update values in a nil map in Go?
No, a nil map cannot be written to. You must initialize the map before adding or updating values.
Click to reveal answer
beginner
Show a simple Go code snippet that adds and updates values in a map.
m := make(map[string]int)
m["apple"] = 5  // add
m["apple"] = 10 // update
Click to reveal answer
What is the correct way to add a new key "banana" with value 3 to a map named fruits in Go?
Afruits["banana"] = 3
Bfruits.add("banana", 3)
Cfruits.insert("banana", 3)
Dfruits.put("banana", 3)
If you assign a value to an existing key in a Go map, what happens?
AThe map is cleared
BA new key is added
CAn error occurs
DThe value for that key is updated
What happens if you try to add a key-value pair to a nil map in Go?
AThe map is automatically initialized
BThe key-value pair is added successfully
CRuntime panic occurs
DThe operation is ignored silently
Which function is commonly used to initialize a map before adding values?
Amake()
Bnew()
Cinit()
Dcreate()
How do you update the value of key "orange" to 7 in a map named fruits?
Afruits.update("orange", 7)
Bfruits["orange"] = 7
Cfruits.set("orange", 7)
Dfruits.change("orange", 7)
Explain how to add and update values in a Go map. Include what happens if the key does not exist.
Think about how assignment works with maps.
You got /3 concepts.
    What must you do before adding or updating values in a Go map to avoid runtime errors?
    Consider what happens if the map is nil.
    You got /3 concepts.