string 给定字符串时 strconv.Atoi() 抛出错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36927486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
strconv.Atoi() throwing error when given a string
提问by dead beef
When trying to use strconv on a variable passed via URL(GET variable named times), GoLang fails on compilation stating the following:
当尝试在通过 URL 传递的变量上使用 strconv(GET 变量命名时间)时,GoLang 编译失败,说明以下内容:
multiple-value strconv.Atoi() in a single-value context
单值上下文中的多值 strconv.Atoi()
However, when I do reflect.TypeOf I get string as the type, which to my understanding is the correct type of argument.
但是,当我进行reflect.TypeOf 时,我将字符串作为类型,据我所知,这是正确的参数类型。
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
}
回答by Cerise Limón
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:
该错误告诉您strconv.Atoi
(int
和error
)的两个返回值用于单个值上下文(对 的赋值time
)。将代码更改为:
time, err := strconv.Atoi(times)
if err != nil {
// handle error
}
回答by Thirumalai Parthasarathi
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.
这会将转换后的数字存储在其中,num
但通过将其分配给空白标识符来丢弃错误。
But do note that once a value is assigned to _
it cannot be referenced again. i.e.
但请注意,一旦为_
它分配了一个值,就不能再次引用它。IE
num, _ := strconv.Atoi(numAsString)
fmt.Println(_) // won't compile. cannot reference _