V
V
Vladimir Grabko2016-09-30 02:27:20
go
Vladimir Grabko, 2016-09-30 02:27:20

Why has the behavior of if changed?

func ErrKeyNotExists() error {
  return errors.New("key not exists")
}

if ErrKeyNotExists() == ErrKeyNotExists() {
  log.Println("ok")
} else {
  log.Println("err")
}

Why does it return "err"? I have a lot of such functions in my code, and after updating to 1.7 everything broke.
UPD.
Because errors returns a reference, the if looks for the same address, not the value.
Checked with this code
q := 1
w := 1
if &q == &w {
  log.Println("ok")
} else {
  log.Println("err")
}

How to force if to compare value?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-09-30
@VGrabko

if ErrKeyNotExists().Error() == ErrKeyNotExists().Error() {
If nil can be returned, then additional checks must be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question