3

So I have a Go variable table map[string]string with some entries. I can access the map values using string keys as expected:

table["key"] // ok

But when I try to access the map with a string key retrieved from os.Stdin...

reader, _ := bufio.NewReader(os.Stdin)
key, _ := reader.ReadString('\n') // type "key" (no quotations), press enter
value, _ := table[key] // no value :(

What could be wrong?

0

2 Answers 2

3

The documentation about ReadString says:

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.

So the key variable contains the key string plus \n (or \r\n on Windows), and it cannot be found in the map.

Sign up to request clarification or add additional context in comments.

Comments

2

Make sure your key don't include the delimiter '\n' included by bytes.ReadString():

(and more generally, don't ignore the return values, especially the errors)

See this runnable(!) example on http://ideone.com/qgvsmF:

package main

import "bufio"
import "fmt"
import "os"

func main() {
    table := make(map[string]string)

    table["key1"] = "val1"
    table["key2"] = "val2"
    table["key3"] = "val3"

    fmt.Println("Enter a key (followed by Return):")
    reader := bufio.NewReader(os.Stdin)
    input, err := reader.ReadString('\n')
    if err != nil {
        panic(err)
    }

    val, ok := table[input]
    fmt.Println("val for key '" + input + "' = '" + val + "'(" + fmt.Sprintf("%v", ok) + ")")
}

It will show a key equals to:

'key2
'

Remove the last character of your string, as in this runnable example:

input = strings.TrimRight(input, "\r\n")

Output:

Enter a key (followed by Return):
val for key 'key2' = 'val2'(true)

4 Comments

Ok, so basically I just needed to strings.Trim the input. Thanks!
@marcioAlmada trim, or input[:len(input)-1], as I have edited the answer. ideone.com/qgvsmF does illustrate it.
Not sure if the '\n' is compatible with all platforms, BTW. Maybe on windows you need to use '\r'?
@marcioAlmada true, I have replaced it with input = strings.Trim(input, "\r\n")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.