-1

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

PatriackLiang
  • 241
  • 1
  • 8
  • 3
    From the documentation: "New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical." The documentation consists of two short sentences of which the second is the answer to your question. It is worth consulting the official documentation first and reading it all. – Volker Apr 03 '20 at 05:26

2 Answers2

6

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
0

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

Zombo
  • 1
  • 62
  • 391
  • 407