-1

Can anyone please help me understand why "if err == errEOF" is not evaluating to TRUE and its only works with io.EOF. I know the Strings.Read function is returning io.EOF, but why can't we use the same type and value to evaluate the err?

https://play.golang.org/p/bCp4bZjKW-K

package main

import (
    "errors"
    "fmt"
    "strings"
    "io"
)

var errEOF = errors.New("EOF")

func main() {
    r := strings.NewReader("ABCDEFGH")

    buf := make([]byte, 4)
    for {
        n, err := r.Read(buf)

        fmt.Println(n, err, buf[:n])
        //if err == io.EOF { //Loop is breaking only when i use io.EOF
        if err == errEOF { // If i use my own ErrEOF value, It is Not Breaking, Going forever

            break
        }
    }
}

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 2
    Each call to `errors.New` returns a distinct error value even if the text is identical. –  Jul 05 '20 at 18:56

1 Answers1

-1
// Package errors implements functions to manipulate errors.
package errors

// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

If you look at the implementation of New in errors package, it just returns a new instance of errorString. So the var EOF = errors.New("EOF") from package io and your definition are two different errors altogether.

You should not be doing this, but the only way your errEOF will work is if you compare err.String() to errEOF.String(). But you should not be doing this anyways.

poWar
  • 745
  • 6
  • 15