Go – 验证的数据类型

huangapple go评论83阅读模式
英文:

Go - Data types for validation

问题

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

例如,要验证字符串是否有20个字符,我尝试了以下代码:

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

type Account struct {
  domain   string
  username string
  created  Date
}

但是它失败了,因为Date不是一个类型。

英文:

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

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.

答案1

得分: 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) {
	// 日期格式:2006-01-12T06:06:06Z
	if len(date) == 0 {
		// 默认为今天
		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)
}
英文:

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

答案2

得分: 1

您可能需要使用标准库中的Time类型。文档

英文:

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

huangapple
  • 本文由 发表于 2010年4月14日 18:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/2636485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定