1 回答

TA貢獻1850條經驗 獲得超11個贊
您可以在 a 中列出多種類型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 found
Error1 or Error 2 found
other 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()
}
- 1 回答
- 0 關注
- 150 瀏覽
添加回答
舉報