Welcome to another engaging tutorial! Today, we're diving into Go's powerful data structure called Map. Let's get started! š
A Map (or Dictionary) in Go is a collection of key-value pairs. The keys are unique and the values can be of any data type.
To declare a Map, we use the map keyword followed by the key and value data types in parentheses. For instance, if we want a map where keys are strings and values are integers, it would look like this:
mapName := map[string]int{}š Note: Don't forget to initialize your Map. If you don't, Go will return an empty map with no keys or values.
You can access the value of a map using its key. If the key doesn't exist, Go will return the zero value of the corresponding type. To modify a value, simply reassign it to the key.
mapName := map[string]int{
"apple": 100,
"banana": 200,
}
value := mapName["apple"] // Accessing the value of the key "apple"
mapName["orange"] = 150 // Adding a new key-value pairTo remove a key-value pair, you can use the delete function.
delete(mapName, "banana") // Removing the key-value pair associated with "banana"You can iterate through a Map using a for loop. Go will automatically loop through the key-value pairs.
for key, value := range mapName {
fmt.Println("Key:", key, "Value:", value)
}What is the purpose of the `delete` function in Go Maps?
What is a Map in Go? A: A collection of key-value pairs B: A collection of values C: A collection of keys Correct: A
How do you declare a Map in Go?
A: By using the map keyword
B: By using the mapName := map[keyType]valueType syntax
C: By using the mapName = {} syntax
Correct: B
How do you access the value of a Map in Go?
A: By using the getValue(key) function
B: By using the key directly
C: By using the mapName[key] syntax
Correct: C
How do you modify the value of a Map in Go?
A: By using the modifyValue(key, newValue) function
B: By reassigning the value to the key
C: By using the mapName[key] = newValue syntax
Correct: C
How do you remove a key-value pair from a Map in Go?
A: By using the delete(mapName, key) function
B: By using the remove(key) function
C: By setting the key's value to nil
Correct: A
How do you loop through a Map in Go?
A: By using a for loop and the range keyword
B: By using a while loop
C: By using a for-each loop
Correct: A
That's it for today! Keep practicing and happy coding! š¤š»