Go 如何基于错误断言具体类型

Go 如何基于错误断言具体类型,go,type-assertion,Go,Type Assertion,如何断言变量是具体类型而不是基类型 import "errors" import "fmt" type NotFound error func test() { e := errors.New("some error") notFound := NotFound(errors.New("404")) _, ok := notFound.(NotFound) //returns t

如何断言变量是具体类型而不是基类型

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
 
}
有没有办法只声明具体类型而不声明基类型

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
 
}
连接至游乐场:


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

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

那么有没有办法检查类型?
e.(NotFound)
表示“e是否实现NotFound”,因为NotFound是一个接口。要么声明一个
NotFound=errors.New(“NotFound”)
并选中
err==NotFound
,要么用
Error()string
方法声明一个具体的
type NotFound struct{}
,这样就可以使用type-assertion。忘记错误是接口而不是结构。谢谢你的解释。我将类型更改为带有错误变量的struct,现在断言可以工作了