场景
package main
import (
"fmt"
"os"
)
func Foo() error {
var err *os.PathError = nil
// …
return err
}
func main() {
err := Foo()
fmt.Println(err) // <nil>
fmt.Println(err == nil) // false
//fmt.Println(err == (*os.PathError)(nil)) // true
}
原因
An interface value is equal to nil only if both its value and dynamic type are nil. In the example above, Foo() returns [nil, *os.PathError] and we compare it with [nil, nil].
You can think of the interface value nil as typed, and nil without type doesn’t equal nil with type. If we convert nil to the correct type, the values are indeed equal.
interface返回值只有在值和类型都为nil的情况下等于nil.在上面的例子中,Foo()返回[nil, *os.PathError],我们用[nil, nil]和之比较
你可以想象interface类型的nil为有类型的nil,没有类型的nil不能与没有类型的nil. 如果我们转换nil类型到正确的类型,则值的确相等
解决方法
-
打开上面代码的最后一行注释,做强制类型转换
-
如下:
func Foo() (err error) { // … return // err is unassigned and has zero value [nil, nil] } func main() { err := Foo() fmt.Println(err) // <nil> fmt.Println(err == nil) // true }
参考
www.zhihu.com/question/45… 代理示例来自: yourbasic.org/golang/gotc…