问题描述
在我的应用中,我使用 validator.v9
验证我的模型。验证后,我可以投射错误
界面,并且成功,我在控制台上看到'OK'
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}
}
但是如果我尝试将此包装的对象转换回 validator.ValidationErrors
在相同的函数中,从它上面的第一种情况开始,仅次于转换失败
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")
}
我在控制台中看到
ValidateModel: OK
ValidationError: FALSE
如何从包装对象中进行此转换?
How can I make this cast work from wrapped object?
ValidationErrors
from gopkg.in/go-playground/validator.v9
看起来像这样
ValidationErrors
from "gopkg.in/go-playground/validator.v9"
looks like this
type ValidationErrors []FieldError
func (ve ValidationErrors) Error() string {
//.....
}
推荐答案
您的 errValidation
类型和 validator.ValidationErrors
类型是完全不同的不同类型。如果接口值包含具体类型 errValidation
的值,则不能键入声明另一个具体类型的值,只有 errValidation
。
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
.
所以这将起作用:
e := ValidationError(errors.New("some err"))
if _, ok := e.(errValidation); ok {
fmt.Println("ValidationError: OK")
} else {
fmt.Println("ValidationError: FALSE")
}
然后将输出(在):
ValidationError: OK
这篇关于如果包装对象,将Golang转换为自定义类型会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!