Create a custom type with constraint in Go -
how create custom type in go valid values can accepted? example, want create type called "names" underlying type string. can accept values "john", "rob" or "paul". other value return error. i've create following program in simplistic way represent achieve.
http://play.golang.org/p/jzzwalsixz
what best way write code?
you (http://play.golang.org/p/jair_0a5_-):
type name struct { string } func (n *name) string() string { return n.string } func newname(name string) (*name, error) { switch name { case "john": case "paul": case "rob": default: return nil, fmt.errorf("wrong value") } return &name{string: name}, nil }
golang not provide operator overload can't make check while casting or affecting value.
depending on trying do, might want (http://play.golang.org/p/uxtnhknrxk):
type name string func (n name) string() string { switch n { case "john": case "paul": case "rob": default: return "error: wrong value" } return string(n) }
Comments
Post a Comment