0

If I have this pure function:

func PureFunction(x int) string {
    switch x {
    case 0:
        return "String zero"
    case 4:
        return "String four"
    default:
        return "Default string"
    }
}

and want to use it in a constant declaration like this:

const str1 = PureFunction(0)
const str1 = PureFunction(4)
const str1 = PureFunction(5)

I get the errors:

PureFunction(0) (value of type string) is not constant
PureFunction(4) (value of type string) is not constant
PureFunction(5) (value of type string) is not constant

In theory the compiler should be able to see that these values are constant.

Is there a way to do something like this? Like defining the function as pure or some other trick to help the compiler?

Kris10an
  • 548
  • 3
  • 23

2 Answers2

3

The function has to be evaluated, so it's not a constant and can't be used as such.

What you can use instead is a var.

Constants are defined as:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

Using var:

var str1 = PureFunction(0)
var str1 = PureFunction(4)
var str1 = PureFunction(5)
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • I know this. My question was more about if there is any way to force the compiler to calculate the value at compile time instead of runtime as it will never change. – Kris10an Dec 22 '21 at 12:51
2

Constants must be able to be assigned at compile time. The value of a const can not be the result of a runtime calculation. Functions are evaluated in runtime, so can not be used to declare a const.

If you even did something like this where value won't change at all, compiler would still give you an error.

  • I know this. My question was more about if there is any way to force the compiler to calculate the value at compile time instead of runtime as it will never change. – Kris10an Dec 22 '21 at 12:51