duanhuilao0787 2018-08-16 10:27 采纳率: 100%
浏览 312
已采纳

如果包装对象,将Golang强制转换为自定义类型会失败

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条回答 默认 最新

  • douchao1864 2018-08-16 10:35
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧