2010-04-14 55 views
4

如何为Go创建新数据类型,以便在创建新变量(该类型)时检查/验证其模式?Go - 用于验证的数据类型

例如,要验证一个字符串有20个字符,我想:

// 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 
} 

但由于日期是不是一个类型的失败。

+0

为什么这是社区wiki? – peterSO 2010-04-14 15:13:11

回答

3

在您的示例中,您将Date定义为变量,然后尝试将其用作类型。

我的猜测是你想要做这样的事情。

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) 
}