go - 如何修复 linter 警告 `Error return value is not checked`?

标签 go linter

我正在调用错误类型值的方法(代码示例中的 foo())。我不在乎这个结果。什么是正确的代码风格编写方式? Errcheck linter 让我检查这个错误。

//for example, same method may be called from imported entity
func foo() error {
   if err := someFunction(); err != nil {
       return err
   }
   return nil
}

func process() {
   //linter doesn't like this
   foo()

   //this way leads to unused variable error
   err := foo()

   //is this clean way?
   _ = foo()

  return 
}

最佳答案

是的,将其分配给通配符变量是忽略错误的好方法。但强烈反对整个做法(忽略错误)。以下是“Effective Go”对此的评价:

Occasionally you'll see code that discards the error value in order to ignore the error; this is terrible practice. Always check error returns; they're provided for a reason.

   // Bad! This code will crash if path does not exist.
    fi, _ := os.Stat(path)
    if fi.IsDir() {
        fmt.Printf("%s is a directory\n", path)
    }

关于go - 如何修复 linter 警告 `Error return value is not checked`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691931/

相关文章:

reactjs - 为什么 prettier 会自动插入空插值代码字符?

node.js - 在本地而不是远程导入 Go 包

go - VScode golang调试错误__debug_bin : Permission Denied

ruby-on-rails - Atom-Editor:Rubocop 不适用于 atom

css - 在某些情况下禁用 stylelint 警告

atom-editor - 如何在 Atom 的 CSLint 中使用 .csslintrc 来忽略规则?

go - Go中 slice 的通用类型

javascript - 如何使用 fetch API 将字符串发送到服务器

go - 为什么 Go 根据我声明缓冲区的位置设置不同的内容类型

javascript - Codemirror 的 SCSS linter