dse55384 2018-04-30 04:12
浏览 348
已采纳

Golang未定义:err

I am trying out the simple following conversion program.

package main

import (
  "fmt"
  "strconv"
)

func main(){
  var numStr string="2213"
  var numVar int64
  numVar,err=strconv.ParseInt(numStr,10,64)
  fmt.Println(numVar)
}

The above throws the following compilation error.

undefined: err

Then I tried to define the err, error variable.

package main

import (
  "fmt"
  "strconv"
)

func main(){
  var numStr string="2213"
  var numVar int64
  var err error
  numVar,err=strconv.ParseInt(numStr,10,64)
  fmt.Println(numVar)
}

But then the compiler throws the following error this time.

err declared and not used

I referred to the following stackoverflow question Undefined err variable but did not get complete understanding of the behavior and hence asking the question here.

  • 写回答

1条回答 默认 最新

  • doupacan2098 2018-04-30 04:40
    关注

    You declare err:

    var err error
    

    and then you assign something to it:

    numVar,err=strconv.ParseInt(numStr,10,64)
    

    but then you don't look at err or access it. Just assigning something a value doesn't count as using it, you have to look at err:

    numVar,err=strconv.ParseInt(numStr,10,64)
    if err != nil {
      // Complain or something here
    }
    

    If you really don't want to bother with the error, then say so by using the blank identifier:

    numVar, _ = strconv.ParseInt(numStr, 10, 64)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Linux环境下CA证书更新问题
  • ¥60 微信小程序如何上传QQ聊天文件
  • ¥300 开发的系统遭到无良商家的破解,请问如何防止再次发生,并追回损失
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上
  • ¥15 魔霸ROG7 pro,win11.息屏后会显示黑屏,如图,如何解决?(关键词-重新启动)
  • ¥15 有没有人知道这是哪里出了问题啊?要怎么改呀?