gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:31:00 50 4
gpt4 key购买 nike

我正在调用错误类型值的方法(代码示例中的 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/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com