How do I access a map record using a string key stored in a variable in Go?
So, I have a Go variable table map[string]string
with some elements. I can access the map values ββusing string keys as expected:
table["key"] // ok
But when I try to access the map using the string key obtained 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?
source to share
Make sure your key doesn't have the delimiter ' \n
' included bytes.ReadString()
:
(and generally don't ignore return values, especially errors)
Check out this example (!) At 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 equal to:
'key2
'
Remove the last character of your string like in this runnable example
input = strings.TrimRight(input, "\r\n")
Output:
Enter a key (followed by Return):
val for key 'key2' = 'val2'(true)
source to share
The documentation about ReadString says:
ReadString reads until the first occurrence of delim in the input, returning a string containing 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 on the map.
source to share