简体   繁体   English

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

[英]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游乐场链接: https://play.golang.org/p/qXYZlbKR92l

NotFound is an interface type as mentioned in the accepted answer. NotFound 是接受的答案中提到的接口类型。

NotFound is not a concrete type. NotFound不是一个具体的类型。 Both error and NotFound are interface types. errorNotFound都是接口类型。 They are both defined as interfaces containing Error() string method, and thus, they are equivalent.它们都被定义为包含Error() string方法的接口,因此它们是等价的。 The same type assertion would not work with non-interface types.相同的类型断言不适用于非接口类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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