Checking if a key exists in a map

Report a typo

Create a program that takes as an input a string key, and then uses an if statement to check if the key exists within the fruits map.

For example, if the key input is pear, your program should output: "The fruit pear 🍐 is in the map".

And in case the key input is a fruit that doesn't exist in the map e.g. kiwi, your program should output: "The fruit kiwi is not in the map".

Sample Input 1:

pear

Sample Output 1:

The fruit pear 🍐 is in the map

Sample Input 2:

kiwi

Sample Output 2:

The fruit kiwi is not in the map
Write a program in Go
package main

import "fmt"

func main() {
// DO NOT delete the code block below!
fruits := map[string]string{"pear": "🍐", "apple": "🍎", "banana": "🍌"}
var key string
fmt.Scanln(&key)

// Write below the code to check if the input key exists in the map:
// Try to use `ok` as the check variable name to follow the Go code style conventions!
if val, ? := fruits[?]; ? {
fmt.Println("The fruit", ?, ?, "is in the map")
return
}
fmt.Println("The fruit", ?, "is not in the map")
}
___

Create a free account to access the full topic