在Go中创建具有约束的自定义类型

How do I create a custom type in Go where only valid values can be accepted? For example, I want to create a type called "Names" where its underlying type is a string. However it can only accept the values "John", "Rob" or "Paul". Any other value will return an error. I've create the following program in a very simplistic way just to represent what I would like to achieve.

http://play.golang.org/p/jzZwALsiXz

What would be the best way to write this code?

You could do something like this (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 does not provide operator overload so you can't make the check while casting or affecting value.

Depending on what you are trying to do, you might want to do something like this (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)
}