Why these two errors are not equal

和自甴很熟 提交于 2021-01-20 14:00:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!