go ensure implementation
package main
import (
"fmt"
"reflect"
)
func main() {
// Create a map with string keys and int values
myMap := map[string]int{
"apple": 23,
"banana": 17,
"orange": 9,
}
// Print the initial map
fmt.Println("Initial Map:", myMap)
// Ensure a key "grapes" exists in the map with a value of 13
ensureKeyExists(myMap, "grapes", 13)
// Print the modified map
fmt.Println("Modified Map:", myMap)
}
// Function to ensure a key exists in a map with a specific value
func ensureKeyExists(m map[string]int, key string, value int) {
// Check if the key exists in the map
if _, ok := m[key]; !ok {
// If the key doesn't exist, add it with the specified value
m[key] = value
fmt.Printf("Key '%s' added with value '%d'\n", key, value)
} else {
// If the key already exists, print a message indicating its presence
fmt.Printf("Key '%s' already exists with value '%d'\n", key, m[key])
}
}
Explanation:
The code starts with a main package declaration and imports necessary packages:
"fmt"
for formatting and"reflect"
for reflection capabilities.Inside the
main()
function:- A map
myMap
is initialized with string keys and integer values. The initial map content is printed using
fmt.Println
.ensureKeyExists()
is a custom function that ensures a specified key exists in the map with a specific value:- It takes a map (
m
), a key (key
), and a value (value
) as arguments. - It checks if the key exists in the map using the existence check syntax:
if _, ok := m[key]; !ok
. - If the key does not exist (
!ok
), it adds the key-value pair to the map and prints a message confirming the addition. If the key already exists, it prints a message indicating its presence.
In
main()
, theensureKeyExists()
function is called to ensure the key "grapes" exists inmyMap
with a value of 13.Finally, after the function call, the modified map content is printed using
fmt.Println
.