Home > OS >  Using pure functions in a constant declaration
Using pure functions in a constant declaration

Time:12-23

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?

CodePudding user response:

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)

CodePudding user response:

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.

  • Related