Home > Article > Backend Development > mistake. Returns false if it contains slices
Error.Is doesn't seem to work properly when I have an error structure that contains slices nested within it:
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{})) }
return
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{})) }
return
equal: true
................................................................. ......................................................................... ......................................................................................... ............................................................. ............................................................. .......
From the documentation:
So you can do this by writing an Is
method to compare the two slices.
The default error comparison algorithm checks whether the error is equal to the target. Since your error contains a slice, it's not comparable.
The above is the detailed content of mistake. Returns false if it contains slices. For more information, please follow other related articles on the PHP Chinese website!