栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/594974.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号