I would approach it like that, since you can't really restrict the content of a variable:
type NamedString string
// Constants for equality check.
// E.x:
// val, err := NamedStringByValue("a")
// val == Astring returs true
const (
Astring NamedString = "a"
Bstring = "b"
)
func NamedStringByValue(val string) (NamedString, error) {
switch val {
case "a", "b":
return NamedString(val), nil
default:
return "", errors.New("unsupported value")
}
}
If you don't care about the content of the AString
and BString
and you just wanna distinguish them, you could make use of iota
like that:
type NamedString int
// Plus 1, so that default value (0 for ints) can be returned
// in case of an error.
const (
AString NamedString = iota + 1
BString
)
func NamedStringByValue(val string) (NamedString, error) {
switch val {
case "a":
return AString, nil
case "b":
return BString, nil
default:
return 0, errors.New("unsupported value")
}
}