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

类型化地图不支持索引

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?

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿