Search code examples
dictionarygostdin

Read map key from stdin


I have a map from strings to ints, I want to select a value by reading the key from stdin. Simple enough, you may say:

  package main
  import (
           "os"
           "bufio"
           "fmt"
  )
 
 func main() {
         m := map[string]int {
                 "Hello": 1,
                 "Map": 2,
         }
 
         reader := bufio.NewReader(os.Stdin)
         text, err := reader.ReadString('\n')
 
         if err != nil {
                 fmt.Println("Error", err)
                 return
         }
 
         fmt.Println(m[text])
 }

When writing "Hello" to the console this prints out 0, not 1.


Solution

  • If I were to guess, using reader.ReadString appends user input with a \n. So the text field ends up being Hello\n

    Using budio.NewScanner() fixes this problem:

    func main() {
        m := map[string]int{
            "Hello": 1,
            "Map":   2,
        }
    
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        text := scanner.Text()
    
        fmt.Println(m[text])
    }
    

    Output:

    $ go run main.go
    Hello
    1