为什么这两个错误不相等 [英] Why these two errors are not equal
问题描述
我在程序包中创建了一个err并将其与io.EOF进行比较,但是==操作数为false.但是它们的类型和值是相同的吗?为什么==操作数返回false?
I create a err in my package and compare it with io.EOF, but the == operand is false. But their type and value are same? Why == operand return false?
func TestErr(t *testing.T) {
err := errors.New("EOF")
t.Log(err == io.EOF)
t.Logf("io err:%T,%v,%p", io.EOF, io.EOF, io.EOF)
t.Logf("my err:%T,%v,%p", err, err, err)
}
这两个错误不相等,因为它们的指针不相等
These two error are not equal because their pointers are not equal
推荐答案
错误
是一个接口.它包含一个指向基础值的指针. io.EOF
由以下人员创建:
error
is an interface. It contains a pointer to the underlying value. The io.EOF
is created by:
var EOF = errors.New("EOF")
如果您查看 errors.New
:
func New(text string) error {
return &errorString{text}
}
type errorString struct {
s string
}
因此, io.EOF
指向 errorString
结构的实例,并且您创建的错误也指向 errorString
的实例具有相同字符串值的struct,但是两个指针不相同.
So, the io.EOF
points to an instance of errorString
struct, and the error you created also points to an instance of errorString
struct with the same string value, but the two pointers are not the same.
这篇关于为什么这两个错误不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!