1

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?

Ivan
  • 1,801
  • 2
  • 23
  • 40

1 Answers1

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.

Volker
  • 40,468
  • 7
  • 81
  • 87