首页 > 解决方案 > 如何将 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 来迭代呢?

标签: arraysvalidationgogo-playground

解决方案


我找到了答案……使用 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
     }
}

推荐阅读