Search code examples
gotype-assertion

How to assert concrete type based on error


How to assert a variable is of concrete type and not of base type?

import "errors"
import "fmt"

type NotFound error

func test() {
    e := errors.New("some error")
    notFound := NotFound(errors.New("404"))
    
    _, ok := notFound.(NotFound) //returns true as expected
    _, isNotFound := e.(NotFound) //returns true, but i'm expecting false
 
}

Is there a way to assert only the concrete type and not the base type?

Link to the playground : https://play.golang.org/p/qXYZlbKR92l

NotFound is an interface type as mentioned in the accepted answer.


Solution

  • NotFound is not a concrete type. Both error and NotFound are interface types. They are both defined as interfaces containing Error() string method, and thus, they are equivalent. The same type assertion would not work with non-interface types.