Golang: crear un tipo constante y restringir los valores del tipo
Tengo una pregunta sobre los tipos de constantes que están restringidos a ciertos valores y cómo se logra eso en Golang. Digamos que creo un tipounary
que tiene dos valores constantesPositive(1)
yNegative(-1)
y quiero restringir al usuario de ese tipo (unary
) desde la creación de otros valores de tipounary
. ¿Lo logro creando un paquete y haciendo los valoresPositive
yNegative
visible y haciendo el tipounary
restringido al paquete que contiene? Vea el código a continuación, por ejemplo
package unary
type unary int////not visible outside of the package unary
const (
Positive unary = 1//visible outside of the package unary
Negative unary = -1//visible outside of the package unary
)
func (u unary) String() string {//visible outside of the package unary
if u == Positive {
return "+"
}
return "-"
}
func (u unary) CalExpr() int {//visible outside of the package unary
if u == Positive {
return 1
}
return -1
}
¿Es esta la forma correcta de restringir un tipo a ciertos valores constantes?