在Go语言中,只允许使用const组中的值。

huangapple go评论79阅读模式
英文:

Allow only values from const group in Go

问题

假设我有一个函数,它的参数是一个 int。我希望这个函数只接受值为 0、1 或 2 的参数。如果我不想手动检查并返回错误,或者在函数内部处理其他值,而是在编译时检查以避免不必要的错误,那就太好了。

// 只接受 0、1 或 2
func foo(bar int) {
    fmt.Println(bar)
}

为了实现这个目标,我定义了自己的类型和三个常量值:

type MyType int

const (
    Zero MyType = iota
    One
    Two
)

现在,我可以修改函数,使其接受 MyType 而不是 int

func foo(bar MyType) {
    fmt.Println(bar)
}

我可以使用这三个常量之一调用它:

foo(Zero) // 输出 0
foo(One)  // 输出 1
foo(Two)  // 输出 2

而且,它不能使用 int 而不是 MyType 来调用:

i := 5
foo(i) // 报错

它在编译时返回以下错误:cannot use i (type int) as type MyType in argument to foo。这正是我想要的。但是!这个函数仍然可以这样调用:

foo(5) // 可以正常工作并输出 5

因为它从参数中推断出类型(即 MyType,实际上是 int),所以当传递一个无类型的参数时,它会自动将其转换为 MyType

那么,有没有办法定义一个只允许三个已定义常量的函数呢?

英文:

Let's say I have a function that takes as an argument an int. I want this function to only accept values 0, 1 or 2. And it would be great if I didn't have to check this manually and return an error, or handle other values from within the function, but instead check it at compile time to avoid undesirable errors.

// should only accept 0, 1 or 2
func foo(bar int) {
    fmt.Println(bar)
}

Now in order to do this, I defined my own type and 3 constant values for it:

type MyType int

const (
    Zero MyType = iota
    One
    Two
)

Now I can modify my function to accept a MyType instead of an int:

func foo(bar MyType) {
    fmt.Println(bar)
}

And I can call it with any of the three constants:

foo(Zero) // would print 0
foo(One)  // would print 1
foo(Two)  // would print 2

And also, it can't be called with an int instead of a MyType

i := 5
foo(i) // errors

It returns the following error at compile time: cannot use i (type int) as type MyType in argument to foo. Which is actually what I want. BUT! The function can still be called like:

foo(5) // works and prints 5

Because it infers the type from the argument (which is MyType which is actually an int) so when passing an untyped argument it converts it automatically to MyType.

So, is there any way to define a function that only allows one of the 3 defined constants?

答案1

得分: 1

所以,有没有办法定义一个只允许使用三个已定义常量之一的函数?

没有这样的办法。

嗯,你可以使用一些丑陋的技巧,比如使用函数或接口类型,但这并不值得努力。

英文:

> So, is there any way to define a function that only allows one of the 3 defined constants?

No there is not.

Well, you could do ugly hacks with e.g. function or interface types, but that's not worth the effort.

huangapple
  • 本文由 发表于 2017年6月26日 18:56:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/44758146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定