1
比方说,我有一个函数作为参数int
。我希望此函数只接受值0,1或2.如果我不必手动检查并返回error
或处理函数中的其他值,而是在编译时检查它避免不必要的错误。仅允许来自const组中的值
// should only accept 0, 1 or 2
func foo(bar int) {
fmt.Println(bar)
}
现在,为了做到这一点,我定义我自己的类型和3个恒定的值吧:
type MyType int
const (
Zero MyType = iota
One
Two
)
现在我可以修改我的作用是接受,而不是一个int的MyType:
func foo(bar MyType) {
fmt.Println(bar)
}
我可以与任何三个常量调用它:
foo(Zero) // would print 0
foo(One) // would print 1
foo(Two) // would print 2
而且也,它不能可以与int
,而不是MyType
i := 5
foo(i) // errors
它返回在编译时出现以下错误叫:cannot use i (type int) as type MyType in argument to foo
。这实际上是我想要的。但!功能仍然可以称为像:
foo(5) // works and prints 5
因为它推断从参数的类型(这是的MyType这实际上是一个int),从而使一个无类型参数时,它会自动将其转换到的MyType。
那么,有没有什么办法来定义一个函数,只允许3个定义的常量之一?