【问题标题】:strconv.Atoi() throwing error when given a stringstrconv.Atoi() 给定字符串时抛出错误
【发布时间】:2016-04-29 00:12:45
【问题描述】:

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

单值上下文中的多值 strconv.Atoi()

但是,当我使用 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
}

【问题讨论】:

    标签: string go atoi strconv


    【解决方案1】:

    错误告诉您来自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)
    

    【讨论】:

    • 感谢这解决了这个问题。不过,在 Go 中函数可以返回不止一种类型的值,这很奇怪。哪个订单时间和错误有关系吗?
    • @deadbeef:多次返回是该语言的基本特征之一。我建议至少通过Tour of Go 了解该语言的工作原理
    • @cerise 它对我有用。
    【解决方案2】:

    虽然这个问题已经得到回答,而且这个问题已经很老了,但我认为补充接受的答案会很好。

    当函数返回问题中的多个值时,如果不需要任何值,则可以使用 空白标识符 _ 将其丢弃,如下所示。

    num, _ := strconv.Atoi(numAsString)
    

    这会将转换后的数字存储在 num 中,但通过将错误分配给空白标识符来丢弃错误。

    但请注意,一旦将值分配给_,就不能再次引用它。即

    num, _ := strconv.Atoi(numAsString)
    fmt.Println(_) // won't compile. cannot reference _
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2018-08-11
      • 2014-02-01
      • 2021-06-03
      • 2019-11-02
      相关资源
      最近更新 更多