【问题标题】:How to convert an HTML form value into an int in Golang如何在 Golang 中将 HTML 表单值转换为 int
【发布时间】:2013-10-08 05:38:54
【问题描述】:

我的测试处理程序代码在这里:

func defineHandler(w http.ResponseWriter, r *http.Request) {
    a := strconv.ParseInt(r.FormValue("aRows")[0:], 10, 64);
    b := r.FormValue("aRows");
    fmt.Fprintf(w, "aRows is: %s", b);
}

编译时返回的错误如下: "单值上下文中的多值 strconv.ParseInt()"

我认为这与 FormValue 中的信息格式有关,我只是不知道如何缓解。

【问题讨论】:

    标签: html go forms typeconverter strconv


    【解决方案1】:

    表示strconv.ParseInt有多个返回值(int和一个error),所以你需要这样做:

    a, err := strconv.ParseInt(r.FormValue("aRows")[0:], 10, 64);
    if err != nil {
      // handle the error in some way
    }
    

    【讨论】:

    • 没那么尴尬。他们可以设计了语言,以便您的原始代码是正确的。许多语言中的parseInt 是这样的:如果出现错误,它会抛出异常或返回NaN 或其他东西。 Go 以这种方式设计,以敦促您考虑错误并处理它们。这需要一些时间来适应。
    猜你喜欢
    • 1970-01-01
    • 2014-12-30
    • 2012-09-15
    • 2018-07-04
    • 1970-01-01
    • 2018-10-08
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多