英文:
why errors don't match nil ? Go
问题
为什么当你使用负比较将错误与nil进行比较时,会得到预期的输出,但是当你尝试使用'正'运算符进行比较时,它却'不起作用'?我认为代码如下所示:
package main
import "fmt"
import "errors"
func main() {
err := makeError
if err != nil {
fmt.Println("as expected")
err = noError
if err == nil {
fmt.Println("as expected")
} else {
fmt.Println("Why no error ?")
}
}
}
func makeError() error {
return errors.New("error!")
}
func noError() (err error) {
return
}
英文:
Why when you use negatively compare an error with nil if provides the expected output but when you try to compare it using the 'positive' operator it 'doesn't work'? I think the code See below
package main
import "fmt"
import "errors"
func main() {
err := makeError
if err != nil {
fmt.Println("as expected")
err = noError
if err == nil {
fmt.Println("as expected")
} else {
fmt.Println("Why no error ?")
}
}
}
func makeError() error {
return errors.New("error!")
}
func noError() (err error) {
return
}
答案1
得分: 4
问题在于你没有调用函数,而是将函数本身赋值给变量。所以 err
的值始终与 nil
不同。
示例:
func foo() error {
return nil
}
func bar() error {
return errors.New("error")
}
// err 将与 foo 函数相同
// 然后你可以执行 err()
err := foo
// err 将是一个错误变量,在这种情况下为 nil
// err != nil 将返回 false
err := foo()
// err 将是一个错误变量,等同于 errors.New("error")
err := bar()
如果你尝试创建变量然后再对其赋值,编译器会报错(如预期所示)。示例:
func foo() error {
return nil
}
var err error
err = foo
将会得到以下编译器错误:
cannot use foo (type func() error) as type error in assignment:
func() error does not implement error (missing Error method)
在 playground 中可以尝试。
英文:
The problem is that you don't call your functions, but assign the function itself to your variables. So the err
value is always different from nil
.
Example:
func foo() error {
return nil
}
func bar() error {
return errors.New("error")
}
// err will be the same as the foo function
// you can then do err()
err := foo
// err will be an error var, nil in this case
// err != nil will return false
err := foo()
// err will be an error var, equivalent to errors.New("error")
err := bar()
If you try to create the variable then assign to it, your compiler will yell at you (as expected). Example:
func foo() error {
return nil
}
var err error
err = foo
will give you the following compiler error
> cannot use foo (type func() error) as type error in assignment:
> func() error does not implement error (missing Error method)
In the playground
答案2
得分: 4
在你的示例代码中,err
不是一个错误值。通过以下赋值语句:
err := makeError
err
的类型是func() error
。err != nil
成功是因为makeError
函数不是nil
。同样地,noError
也是一个函数,并且不等于nil
。
如果你实际调用这些函数,你应该会得到你期望的结果。
英文:
In your example code, err
is not an error value. With the following assignment:
err := makeError
err
is of type func() error
. The err != nil
succeeds because the makeError
function is not nil
. Similarly, noError
is also a function and not equal to nil
.
If you actually call the functions, you should get the results you expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论