您可以在中列出多个类型
case,这样便可以完成您想做的事情:
switch t := param.(type) {case Error1, Error2: fmt.Println("Error1 or Error 2 found")default: fmt.Println(t, " belongs to an unidentified type")}测试它:
printType(Error1{})printType(Error2{})printType(errors.New("other"))输出(在Go Playground上尝试):
Error1 or Error 2 foundError1 or Error 2 foundother belongs to an unidentified type
如果要对错误进行“分组”,另一种解决方案是创建“标记”接口:
type CommonError interface { CommonError()}这
Error1与
Error2必须实现:
func (Error1) CommonError() {}func (Error2) CommonError() {}然后您可以执行以下操作:
switch t := param.(type) {case CommonError: fmt.Println("Error1 or Error 2 found")default: fmt.Println(t, " belongs to an unidentified type")}用相同的方法测试,输出是相同的。在Go Playground上尝试一下。
如果您想将
CommonErrors 限制为“ true”错误,请同时嵌入
error接口:
type CommonError interface { error CommonError()}


