亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我們可以為 Go 中的錯誤創建子類型嗎?

我們可以為 Go 中的錯誤創建子類型嗎?

Go
明月笑刀無情 2023-06-26 15:31:07
我想在 Go 中創建層次結構錯誤。我們可以在 Go 中實現這一點嗎?例如,我有以下兩個錯誤。type Error1 struct {    reason string    cause error}func (error1 Error1) Error() string {    if error1.cause == nil || error1.cause.Error() == "" {        return fmt.Sprintf("[ERROR]: %s\n", error1.reason)    } else {        return fmt.Sprintf("[ERROR]: %s\nCaused By: %s\n", error1.reason, error1.cause)    }}type Error2 struct {    reason string    cause error}func (error2 Error2) Error() string {    if error2.cause == nil || error2.cause.Error() == "" {        return fmt.Sprintf("[ERROR]: %s\n", error2.reason)    } else {        return fmt.Sprintf("[ERROR]: %s\nCause: %s", error2.reason, error2.cause)    }}我想要一個由兩個子類型和CommonError組成的錯誤類型,以便我可以執行以下操作。Error1Error1func printType(param error) {    switch t := param.(type) {    case CommonError:        fmt.Println("Error1 or Error 2 found")    default:        fmt.Println(t, " belongs to an unidentified type")    }}有辦法實現這一點嗎?編輯:在類型切換中,我們可以像這樣使用多個錯誤: case Error1, Error2:但是當我有大量錯誤時,或者當我需要對模塊內的錯誤進行一些抽象時,這種方法不會是最好的方法。
查看完整描述

1 回答

?
慕蓋茨4494581

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()

}


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號