如何在Go中创建多级错误子类型

如何在Go中创建多级错误子类型,第1张

如何在Go中创建多级错误子类型

您使用了该

UniversalError()
方法,但是没有将其添加到“定义”接口中,因此请执行以下 *** 作:

type UniversalError interface {    CommonError1    UniversalError()}

而你想

Error3
成为一个
UniversalError
。对于
Error3
成为一个
UniversalError
,它必须实现所有的方法:
UniversalError()
CommonError1()
。因此,您必须同时添加这两种方法:

func (Error3) CommonError1()   {}func (Error3) UniversalError() {}

经过这些更改,输出将是(在Go Playground上尝试):

**** Types *****Error belongs to an unidentified typeError belongs to an unidentified typeCommonError1 found, but Does not belong to Error1 or Error2

提示: 如果要在编译时保证某些具体类型实现某些接口,请使用空白变量声明,如下所示:

var _ UniversalError = Error3{}

上面的声明将的值分配给

Error3
type的变量
UniversalError
。不应该
Error3
满足
UniversalError
,您会得到一个编译时错误。上面的声明将不会引入新变量,因为使用了空白标识符,这只是编译时检查。

如果要删除该

Error3.CommonError1()
方法:

//func (Error3) CommonError1()   {}func (Error3) UniversalError() {}

然后,您将立即收到编译时错误:

./prog.go:49:5: cannot use Error3 literal (type Error3) as type UniversalError in assignment:    Error3 does not implement UniversalError (missing CommonError1 method)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5600357.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存