Add new types to Go
- by nevalu
I'm trying add new types for that been managed/used as in Go core types.
To create new types is anything very interesting to validate data before of send it to a non-SQL DBMS or to check data from a form.
Go uses univeral constants to define them at global level:
var DateType = universe.DefineType("date", universePos, &dateType{})
In this case they're defined to be called from a package like types:
var Date = &dateType{}
I get these errors:
test.go:58: o.lit undefined (cannot refer to unexported field lit)
test.go:62: *dateType is not Type
missing Pos() token.Position
The code is based on:
http://github.com/tav/go/blob/master/src/pkg/exp/eval/value.go
http://github.com/tav/go/blob/master/src/pkg/exp/eval/type.go
package main
import (
"exp/eval"
"fmt"
// "go/token"
)
// http://github.com/tav/go/blob/master/src/pkg/exp/eval/value.go
type DateValue interface {
eval.Value
Get(*eval.Thread) string
Set(*eval.Thread, string)
}
/* Date */
type dateV string
func (v *dateV) String() string { return fmt.Sprint(*v) }
func (v *dateV) Assign(t *eval.Thread, o eval.Value) { *v = dateV(o.(DateValue).Get(t)) }
func (v *dateV) Get(*eval.Thread) string { return string(*v) }
func (v *dateV) Set(t *eval.Thread, x string) { *v = dateV(x) }
// http://github.com/tav/go/blob/master/src/pkg/exp/eval/type.go
type Type interface {
eval.Type
// isDate returns true if this is a date type.
isDate() bool
}
/* Common type */
type commonType struct{} // added
func (commonType) isDate() bool { return false }
/* Date */
type dateType struct {
commonType
}
// * It should not be an universal constant
//var universePos = token.Position{"<universe>", 0, 0, 0} // added
//var DateType = universe.DefineType("date", universePos, &dateType{})
var Date = &dateType{}
func (t *dateType) compat(o Type, conv bool) bool {
t2, ok := o.lit().(*dateType)
return ok && t == t2
}
func (t *dateType) lit() Type { return t }
func (t *dateType) isDate() bool { return true }
func (t *dateType) String() string { return "<date>" }
func (t *dateType) Zero() eval.Value {
res := dateV("")
return &res
}
/* Named types */
/*
type NamedType struct {
eval.NamedType
Def Type
}*/
type NamedType struct { // added
// token.Position
Name string
// Underlying type. If incomplete is true, this will be nil.
// If incomplete is false and this is still nil, then this is
// a placeholder type representing an error.
Def Type
// True while this type is being defined.
incomplete bool
methods map[string]eval.Method
}
func (t *NamedType) isDate() bool { return t.Def.isDate() }
/* *********************** */
func main() {
print("foo")
}