首頁  >  文章  >  後端開發  >  錯誤。如果包含切片,則傳回 false

錯誤。如果包含切片,則傳回 false

王林
王林轉載
2024-02-12 16:36:05779瀏覽

错误。如果包含切片,则返回 false

問題內容

當我有一個包含嵌套在其中的切片的錯誤結構時,Error.Is 似乎無法正常工作:

package main

import (
    "errors"
    "fmt"
    "os"
)

type Response struct {
    Details []string
}

type ErrResponseError struct {
    Response Response
}

func (err ErrResponseError) Error() string {
    return "response error"
}

func main() {
    err := ErrResponseError{}
    fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}

返回


equal: false
package main

import (
    "errors"
    "fmt"
    "os"
)

type Response struct {
    Details string // Changed this line
}

type ErrResponseError struct {
    Response Response
}

func (err ErrResponseError) Error() string {
    return "response error"
}

func main() {
    err := ErrResponseError{}
    fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}

返回


equal: true

............................................... .... ........................................... ........... .................................... ................................................ ................................................................ ....

解決方法

來自文件:

因此,您可以透過編寫 Is 方法來比較兩個切片來完成此操作。

預設的誤差比較演算法檢查誤差是否等於目標。由於您的錯誤包含一個切片,因此它不具有可比性。

以上是錯誤。如果包含切片,則傳回 false的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除