如何根据错误断言具体类型

How to assert concrete type based on error

如何断言一个变量是具体类型而不是基本类型?

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
 
}

有没有办法只断言具体类型而不断言基类型?

Link 去游乐场:https://play.golang.org/p/qXYZlbKR92l

NotFound 是接受的答案中提到的接口类型。

NotFound 不是具体类型。 errorNotFound 都是接口类型。它们都被定义为包含 Error() string 方法的接口,因此它们是等价的。相同的类型断言不适用于非接口类型。