简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM