Search⌘ K

Solution Review: Map the Days

Explore Go maps by learning how to declare and initialize key-value pairs, verify the presence of keys, and handle cases when keys do not exist. This lesson helps you understand practical map usage and how to retrieve values safely in Go programs.

We'll cover the following...
Go (1.6.2)
package main
import (
"fmt"
)
var Days = map[int]string{
1:"Monday",
2:"Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"}
func findDay(n int) string {
val,isPresent := (Days[n])
if isPresent{ // what if key is not present
return val
}else{
return "Wrong Key"} // return wrong key if invalid key
}
func main() {
n := 4
fmt.Println(n,":",findDay(n))
n = 0
fmt.Println(n,":",findDay(n))
}

In the above code, outside main at line 6, we make a map Days. The declaration of Days shows that its keys will be of int type and values associated with its keys will be of string type. Initialization is as follows:

  • Key 1 is given Monday as a value.
  • Key 2 is given Tuesday as a value.
  • Key 3 is given Wednesday as a value.
  • Key 4 is
...