Go Map Declaration šŸŽÆ

beginner
24 min

Go Map Declaration šŸŽÆ

Welcome to another engaging tutorial! Today, we're diving into Go's powerful data structure called Map. Let's get started! šŸš€

What is a Map in Go? šŸ“

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.

Declaring a Map in Go šŸ’”

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:

go
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.

Accessing and Modifying Map Entries šŸ’”

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.

go
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 pair

Removing a Key-Value Pair šŸ’”

To remove a key-value pair, you can use the delete function.

go
delete(mapName, "banana") // Removing the key-value pair associated with "banana"

Looping through a Map šŸ’”

You can iterate through a Map using a for loop. Go will automatically loop through the key-value pairs.

go
for key, value := range mapName { fmt.Println("Key:", key, "Value:", value) }
Quick Quiz
Question 1 of 1

What is the purpose of the `delete` function in Go Maps?

Quiz Time šŸŽÆ

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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! šŸ¤–šŸ’»