arrays - 如何将 Go validator.FieldLevel.Field() 转换为字符串数组
问题描述
我有一个具有这种结构的复杂对象。
type People struct {
Objectives []string `validate:"required,ValidateCustom" json:"Objectives"`
}
我需要在枚举中测试列表思考,使用gopkg.in/go-playground/validator.v9
:
//ValidateCustom -- ValidateCustom
func ValidateCustom(field validator.FieldLevel) bool {
switch strings.ToUpper(field.Field().String()) {
case "emumA":
case "enumB":
return true
default:
return false
}
}
这个例子使用了字符串的概念,但是我怎样才能构建到 []string 来迭代呢?
解决方案
我找到了答案……使用 slice 和 Interface
//ValidateCustom -- ValidateCustom
func ValidateCustom(field validator.FieldLevel) bool {
inter := field.Field()
slice, ok := inter.Interface().([]string)
if !ok {
return false
}
for _, v := range slice {
switch strings.ToUpper(v) {
case "enumA":
case "enumB":
return true
default:
return false
}
}
推荐阅读
- javascript - 比较两个 JavaScript 对象并提取匹配属性的键和值
- python - 将函数映射或应用到单个值 - Python 3 中的正确方法
- gradle - 如何发布和使用构建为 fatJar 的 gradle 插件?
- cocoa - 如何插入 NSBezierPath/UIBezierPath 并在位置检索正常向量?
- python - 测试一个整数是否是切片的索引值
- regex - 基于正则表达式批量修改密码查询中的节点
- javascript - 反应“超过最大更新深度。”
- sip - H323 视频与 Freeswitch mod_h323 可能吗?
- javascript - 如何为第三方 react javascript 模块设置@types,以便我可以从 typescript 访问它并使用 webpack 打包它?
- sql-server - 我想将 DATEADD("d",- (DAY(GETDATE())) + 1,GETDATE()) 转换为 YYYY-MM-DD 格式