英文:
strconv.Atoi() throwing error when given a string
问题
尝试使用strconv对通过URL传递的变量(名为times的GET变量)进行转换时,GoLang在编译时出现以下错误:
> multiple-value strconv.Atoi() in a single-value context
然而,当我使用reflect.TypeOf时,我得到的类型是string,根据我的理解,这是正确的参数类型。
我已经尝试解决这个问题几个小时了。我对Go语言还很陌生,对这个问题感到非常沮丧。最后我决定寻求帮助。任何反馈都将不胜感激。
func numbers(w http.ResponseWriter, req *http.Request) {
fmt.Println("GET params were:", req.URL.Query());
times := req.URL.Query()["times"][0]
time := strconv.Atoi(times)
reflect.TypeOf(req.URL.Query()["times"][0]) // 返回string类型
}
英文:
When trying to use strconv on a variable passed via URL(GET variable named times), GoLang fails on compilation stating the following:
> multiple-value strconv.Atoi() in a single-value context
However, when I do reflect.TypeOf I get string as the type, which to my understanding is the correct type of argument.
I have been trying to fix this issue for several hours. I'm new to go and have become pretty frustrated with this problem. I finally decided to ask for help. Any feedback would be appreciated.
func numbers(w http.ResponseWriter, req *http.Request) {
fmt.Println("GET params were:", req.URL.Query());
times := req.URL.Query()["times"][0]
time := strconv.Atoi(times)
reflect.TypeOf(req.URL.Query()["times"][0]) // returns string
}
答案1
得分: 69
错误提示告诉你,strconv.Atoi
的两个返回值(int
和 error
)在单值上下文中被使用(赋值给 time
)。将代码更改为:
time, err := strconv.Atoi(times)
if err != nil {
// 在这里添加处理错误的代码!
}
使用空白标识符来忽略 error
返回值:
time, _ := strconv.Atoi(times)
英文:
The error is telling you that the two return values from strconv.Atoi
(int
and error
) are used in a single value context (the assignment to time
). Change the code to:
time, err := strconv.Atoi(times)
if err != nil {
// Add code here to handle the error!
}
Use the blank identifier to ignore the error
return value:
time, _ := strconv.Atoi(times)
答案2
得分: 12
虽然这个问题已经有答案了,而且问题也相当久远,但我觉得补充一下接受的答案会很好。
当一个函数返回多个值时,如果其中任何一个值不需要,可以使用空白标识符 _
来丢弃它们,如下所示:
num, _ := strconv.Atoi(numAsString)
这将把转换后的数字存储在 num
中,但通过将其赋值给空白标识符来丢弃错误。
但请注意,一旦一个值被赋给 _
,就不能再引用它了。也就是说:
num, _ := strconv.Atoi(numAsString)
fmt.Println(_) // 无法编译,不能引用 _。
英文:
Although this has been answered and the question is quite old, I thought it would be nice to complement the accepted answer.
When a function returns multiple values as in the question, if any of the value is not needed then they can be discarded by using the blank identifier _
as in the following.
num, _ := strconv.Atoi(numAsString)
This would store the converted number in num
but discard the error by assigning it to the blank identifier.
But do note that once a value is assigned to _
it cannot be referenced again. i.e.
num, _ := strconv.Atoi(numAsString)
fmt.Println(_) // won't compile. cannot reference _
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论