mistake. Returns false if it contains slices

王林
Release: 2024-02-12 16:36:05
forward
798 people have browsed it

错误。如果包含切片,则返回 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{}))
}
Copy after login

return


equal: false
Copy after login
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{}))
}
Copy after login

return


equal: true
Copy after login

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!