英文:
How to access a map entry with a string key stored in a variable in Go?
问题
所以我有一个Go变量table map[string]string
,其中包含一些条目。我可以像预期的那样使用字符串键访问映射值:
table["key"] // 正常
但是当我尝试使用从os.Stdin
中获取的字符串键访问映射时...
reader, _ := bufio.NewReader(os.Stdin)
key, _ := reader.ReadString('\n') // 输入 "key"(没有引号),然后按回车
value, _ := table[key] // 没有值 :(
可能出了什么问题?
英文:
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?
答案1
得分: 3
关于ReadString的文档说明如下:
ReadString会一直读取输入,直到遇到第一个分隔符delim,返回一个包含从开头到分隔符(包括分隔符)的字符串。
因此,key变量包含了键字符串加上\n(或Windows上的\r\n),而这个字符串在映射中找不到。
英文:
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.
答案2
得分: 2
确保你的键不包含由bytes.ReadString()
包含的分隔符'\n
':
(更一般地说,不要忽略返回值,尤其是错误)
在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) + ")")
}
它将显示一个等于的键:
'key2
'
[删除字符串的最后一个字符][2],就像这个[可运行的例子][3]中一样:
```go
input = strings.TrimRight(input, "\r\n")
输出:
Enter a key (followed by Return):
val for key 'key2' = 'val2'(true)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论