如何在Go中创建多级错误子类型
我试图在GO中创建错误的子类型。关于这件事 现在我面临着一个有多种类型的问题。以下代码显示了错误类型定义:如何在Go中创建多级错误子类型,go,types,error-handling,subtyping,type-switch,Go,Types,Error Handling,Subtyping,Type Switch,我试图在GO中创建错误的子类型。关于这件事 现在我面临着一个有多种类型的问题。以下代码显示了错误类型定义: /*接口*/ 类型UniversalError接口{ 常见错误1 } 类型CommonError1接口{ 错误 CommonError1() } /*结构*/ 类型Error1结构{ 原因字符串 } 类型Error2结构{ 原因字符串 } 类型Error3结构{ 原因字符串 } /*接口函数实现*/ func(error1 error1)Error()字符串{ 返回fmt.Sprintf(
/*接口*/
类型UniversalError接口{
常见错误1
}
类型CommonError1接口{
错误
CommonError1()
}
/*结构*/
类型Error1结构{
原因字符串
}
类型Error2结构{
原因字符串
}
类型Error3结构{
原因字符串
}
/*接口函数实现*/
func(error1 error1)Error()字符串{
返回fmt.Sprintf(错误1.原因)
}
func(error2 error2)Error()字符串{
返回fmt.Sprintf(错误2.原因)
}
func(error3 error3)Error()字符串{
返回fmt.Sprintf(错误3.原因)
}
func(Error1)CommonError1(){}
func(Error2)CommonError1(){}
func(Error3)UniversalError(){}
当我尝试运行以下代码时:
func main(){
var err1=Error1{reason:“错误原因1”}
var err2=Error2{reason:“Error reason 2”}
var err3=Error3{reason:“Error reason 3”}
fmt.Println(“\n****类型*******”)
打印类型(err1)
打印类型(err2)
打印类型(err3)
}
func打印类型(参数错误){
开关参数(类型){
案例通用错误:
开关参数(类型){
案例1:
开关参数(类型){
案例1:
fmt.Println(“发现错误1”)
案例2:
fmt.Println(“发现错误2”)
违约:
fmt.Println(“找到CommonError1,但不属于Error1或Error2”)
}
违约:
fmt.Println(“发现错误3”)
}
违约:
fmt.Println(“错误属于未识别类型”)
}
}
printType()
函数打印以下内容:
****类型*****
发现错误1
发现错误2
找到CommonError1,但不属于Error1或Error2
我需要将
Error3
类型标识为UniversalError
,而不是CommonError1
。我怎样才能做到这一点?我的方法有什么错误吗?您使用了UniversalError()
方法,但您没有将其添加到接口“definition”中,因此请执行以下操作:
type UniversalError interface {
CommonError1
UniversalError()
}
您希望Error3
成为UniversalError
。要使Error3
成为UniversalError
,它必须实现其所有方法:UniversalError()
和CommonError1()
。因此,您必须添加这两种方法:
func (Error3) CommonError1() {}
func (Error3) UniversalError() {}
通过这些更改,输出将是(在上尝试):
提示:如果您希望在编译时保证某些具体类型实现某些接口,请使用如下空白变量声明:
var _ UniversalError = Error3{}
上述声明将Error3
的值分配给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)
你不能。Go中没有“子类型”,没有父/子类,没有类层次结构,没有继承,没有接口之外的多态性。谢谢你的回答。但是在这种情况下,为什么不将
Error1
和Error2
识别为UniversalError
?这里我需要两个超级类型。1.由Error1
和Error2
->CommonError1
2组成。由CommonError1
和Error3
->通用错误组成。@thisarugeUniversalError
嵌入CustomError1
,而不是相反。如果您想要相反的关系,嵌入应该反映这一点。看起来您希望所有错误都是“通用的”,因此CustomError1
和CustomError2
应该嵌入UniversalError
。实施的方法一定是这样的。哦,我完全误解了。非常感谢。
./prog.go:49:5: cannot use Error3 literal (type Error3) as type UniversalError in assignment:
Error3 does not implement UniversalError (missing CommonError1 method)