小编adr*_*ers的帖子

在Go中验证结构的惯用方法?

我需要验证结构值是否正确,这意味着我需要单独检查每个字段,这对于少量小结构很容易,但我想知道是否有更好的方法来实现它.这就是我现在正在做的事情.

type Event struct {
    Id     int
    UserId int
    Start  time.Time
    End    time.Time
    Title  string
    Notes  string
}

func (e Event) IsValid() error {
    if e.Id <= 0 {
        return errors.New("Id must be greater than 0")
    }
    if e.UserId <= 0 {
        return errors.New("UserId must be greater than 0")
    }
    if e.End <= e.Start {
        return errors.New("End must be after Start")
    }
    if e.Start < time.Now() {
        return errors.New("Cannot create events in the past")
    }
    if e.Title == "" { …
Run Code Online (Sandbox Code Playgroud)

validation go

44
推荐指数
4
解决办法
3万
查看次数

标签 统计

go ×1

validation ×1