ds34222 2017-06-26 10:56
浏览 59

在Go中仅允许const组中的值[重复]

This question already has an answer here:

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?

</div>
  • 写回答

1条回答 默认 最新

  • dongzouban9871 2017-06-26 11:03
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题