Golang cast to a custom type fails if I wrap my ob

2020-04-10 03:08发布

问题:

In my app I use validator.v9 to validate my model. After validation I can cast the error interface and it's successes, I see 'OK' on the console

err := v.ModelValidator.Struct(model)

if _, ok := err.(validator.ValidationErrors); ok {
    fmt.Println("ValidateModel: OK")
} else{
    fmt.Println("ValidateModel: FALSE")
}

I need to wrap this object to another one for future processing

type errValidation struct {
    error
}

func ValidationError(err error) error {
    return errValidation{err}
}

But if I try to cast this wrapped object back to validator.ValidationErrors in the same function just below the cast from a first case above it fails

e := ValidationError(err)
if _, ok := e.(validator.ValidationErrors); ok {
    fmt.Println("ValidationError: OK")
} else{
    fmt.Println("ValidationError: FALSE")
}

I see in the console

ValidateModel: OK
ValidationError: FALSE

How can I make this cast work from wrapped object?

ValidationErrors from "gopkg.in/go-playground/validator.v9" looks like this

type ValidationErrors []FieldError
func (ve ValidationErrors) Error() string {
     //.....
}

回答1:

Your errValidation type and the validator.ValidationErrors type are completely different, distinct types. If an interface value holds a value of concrete type errValidation, you can't type assert another concrete type from it, only errValidation.

So this will work:

e := ValidationError(errors.New("some err"))
if _, ok := e.(errValidation); ok {
    fmt.Println("ValidationError: OK")
} else {
    fmt.Println("ValidationError: FALSE")
}

And output will be (try it on the Go Playground):

ValidationError: OK


标签: go casting