Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeOf with Comparable in errors.Is

I am learning how error comparison works in Go and found something I cannot understand.

Function errors.Is(err, target error) checks if target is Comparable.

func Is(err, target error) bool {
    if target == nil {
        return err == target
    }

    isComparable := reflectlite.TypeOf(target).Comparable()
    for {
        if isComparable && err == target {
            return true
        }

Source

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Which case does this call handle given that all interfaces in Go are comparable and error is an interface?

>Solution :

Interfaces values are comparable, but the comparison can panic at run-time. The specification says:

A comparison of two interface values with identical dynamic types causes a run-time panic if values of that type are not comparable.

The check prevents a panic by skipping the comparison when the target’s concrete type is not comparable.

Here’s an example:

type E []byte
func (e E) Error() string { return string(e) }

var a error = E{}
var b error = E{}
fmt.Println(errors.Is(a, b)) // prints false
fmt.Println(a == b)          // panics because slices are not comparable
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading