gpt4 book ai didi

string - strconv.Atoi() 给定字符串时抛出错误

转载 作者:IT老高 更新时间:2023-10-28 13:06:40 28 4
gpt4 key购买 nike

当尝试对通过 URL 传递的变量(GET 变量命名时间)使用 strconv 时,GoLang 编译失败,说明如下:

multiple-value strconv.Atoi() in a single-value context

但是,当我使用 reflect.TypeOf 时,我将字符串作为类型,据我了解,这是正确的参数类型。

我已经尝试解决这个问题几个小时了。我是新手,对这个问题感到非常沮丧。我终于决定寻求帮助。任何反馈将不胜感激。

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
}

最佳答案

错误告诉你 strconv.Atoi 的两个返回值(interror) 用于单值上下文(对 time 的赋值)。将代码更改为:

   time, err := strconv.Atoi(times)
if err != nil {
// Add code here to handle the error!
}

使用 blank identifier忽略 error 返回值:

   time, _ := strconv.Atoi(times)

关于string - strconv.Atoi() 给定字符串时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927486/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com