Home  >  Article  >  Backend Development  >  mistake. Returns false if it contains slices

mistake. Returns false if it contains slices

王林
王林forward
2024-02-12 16:36:05815browse

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

Question content

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

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

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete