开发者

Go - Data types for validation

How to create a new data type for Go which to can check/validate its schema when is created a new variable (of that t开发者_StackOverflowype)?

By example, to validate if a string has 20 characters, I tried:

// Format: 2006-01-12T06:06:06Z
func date(str string) {
  if len(str) != 20 {
    fmt.Println("error")
  }
}
var Date = date()

type Account struct {
  domain  string
  username string
  created  Date
}

but it fails because Date is not a type.


In your example, you defined Date as a variable and then tried to use it as a type.

My guess is that you want to do something like this.

package main

import (
    "fmt"
    "os"
    "time"
)

type Date int64

type Account struct {
    domain   string
    username string
    created  Date
}

func NewDate(date string) (Date, os.Error) {
    // date format: 2006-01-12T06:06:06Z
    if len(date) == 0 {
        // default to today
        today := time.UTC()
        date = today.Format(time.ISO8601)
    }
    t, err := time.Parse(time.ISO8601, date)
    if err != nil {
        return 0, err
    }
    return Date(t.Seconds()), err
}

func (date Date) String() string {
    t := time.SecondsToUTC(int64(date))
    return t.Format(time.ISO8601)
}

func main() {
    var account Account
    date := "2006-01-12T06:06:06Z"
    created, err := NewDate(date)
    if err == nil {
        account.created = created
    } else {
        fmt.Println(err.String())
    }
    fmt.Println(account.created)
}


You probably want the Time type from the standard library. Documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜