问题
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
回答1:
error
is an interface. It contains a pointer to the underlying value. The io.EOF
is created by:
var EOF = errors.New("EOF")
If you look at errors.New
:
func New(text string) error {
return &errorString{text}
}
type errorString struct {
s string
}
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.
回答2:
If you really want to do this, you can unwrap the errors:
package main
import (
"errors"
"io"
)
func main() {
err := errors.New("EOF")
println(err.Error() == io.EOF.Error())
}
https://golang.org/pkg/builtin#error
来源:https://stackoverflow.com/questions/61004616/why-these-two-errors-are-not-equal