dreamfly2016
2014-07-23 07:42
浏览 2
已采纳

类型化地图不支持索引

I want to extend go-validator to return a better type:

type Error map[string][]error

// Will output the first error when stringified (e.g. for json response).
func (err Error) Error() string {
    for k, errs := range err {
        return fmt.Sprintf("%s value had %s", k, errs[0].Error())
    }

    return "no error"
}

func Validate(v interface{}) error {
    if ok, errs := DefaultValidator.Validate(v); !ok {
        return Error(errs)
    }

    return nil
}

As I am now writing tests for this I ran into the problem that it the typed map Error seems to have lost it indexing capabilities:

err = Validate(Value{
    Foo:      "bar",
    Email:    "foo@bar.me",
    Required: "1234",
})
c.Check(err, check.IsNil)

err, ok := Validate(Value{}).(Error)
c.Check(ok, check.Equals, true)
c.Check(err["Foo"], check.DeepEquals, []error{validator.ErrMin})
c.Check(err["Email"], check.DeepEquals, []error{validator.ErrInvalid})
c.Check(err["Required"], check.DeepEquals, []error{validator.ErrZeroValue})

Returns:

model/validation/validation_test.go:42: invalid operation: err["Foo"] (type error does not support indexing)
model/validation/validation_test.go:43: invalid operation: err["Email"] (type error does not support indexing)
model/validation/validation_test.go:44: invalid operation: err["Required"] (type error does not support indexing)

I also tried to cast to type map[string][]error but got "impossible type assertion".

What is wrong with my approach? How can I get indexing back to work?

图片转代码服务由CSDN问答提供 功能建议

我想扩展 go-validator 返回更好的类型:

  type Error map [string] [] error 
 
 //将输出 字符串化后的第一个错误(例如,对于json响应)。
func(错误错误)Error()字符串{
对于k,错误:=范围错误{
返回fmt.Sprintf(“%s值具有%s”,k  ,errs [0] .Error())
} 
 
返回“无错误” 
} 
 
func Validate(v interface {})错误{
如果可以,错误:= DefaultValidator.Validate(  v)的;  !ok {
返回错误(错误)
} 
 
返回nil 
} 
   
 
 

我现在正在为此编写测试 类型化的地图 Error 似乎已失去索引功能的问题:

  err = Validate(Value {
 Foo:“ bar”  ,
电子邮件:“ foo@bar.me”,
必需:“ 1234”,
})
c.Check(err,check.IsNil)
 
err,确定:= Validate(Value {})  。(错误)
c.Check(确定,检查。等于,true)
c.Check(err [“ Foo”],检查。DeepEquals,[] error {validator.ErrMin})
c.Check(err [“ 电子邮件“],检查。DeepEquals,[]错误{validator.ErrInvalid})
c.Check(err [”必填“],检查。DeepEquals,[]错误{validator.ErrZeroValue})
   
 
 

返回:

 模型/验证/validation_test.go:42:无效操作:err [“ Foo”](类型错误不支持 索引)
model / validation / validation_test.go:43:无效的操作:err [“电子邮件”](类型错误不支持索引)
model / validation / validation_test.go:44:无效的操作:err [“必需 ed“](类型错误不支持索引)
   
 
 

我也尝试过强制转换为 map [string] [] error 类型,

我的方法有什么问题? 如何重新建立索引?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsms21398 2014-07-23 08:22
    已采纳

    It seems like your err variable is initialised with error type. When you do

    err, ok := Validate(Value{}).(Error)
    

    you merely check if err is actually an Error. If you change err there to say errs, it should work.

    Playground example: http://play.golang.org/p/ljNroPzVbd

    打赏 评论

相关推荐 更多相似问题