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

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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试以下简单的转换程序。

  包main 
 
import(
“ fmt” 
“ strconv” 
)
 
func main(){
 var numStr string =“ 2213” 
 var numVar int64 
 numVar,err = strconv。  ParseInt(numStr,10,64)
 fmt.Println(numVar)
} 
   
 
 

上面的代码会引发以下编译错误。

 未定义:err 
   
 
 

然后我尝试定义err错误变量。

 包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)
} 
   
  
 

但是随后编译器这次抛出了以下错误。

  err已声明但未使用
   
 
 <  p>我提到了以下stackoverflow问题未定义的err变量,但并未完全了解行为和 因此在这里问这个问题。 
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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)
    
    打赏 评论

相关推荐 更多相似问题