Concatenate int and string as constant - Golang

Viewed 1349

I am searching for a way to concatenate constant string and constant integer in Golang and save the result as constant as well. My goal is to concatenate math.MaxInt32 to a string like this :

const reportMsg = "the maximum int value is " + math.MaxInt32

I have tried the following :

package main

import (
    "fmt"
    "math"
)

const (
    reportMsg = "the maximum int value is " + string(math.MaxInt32)
    //some other unrelated consts here
)

func main(){
    fmt.Println(reportMsg)
}

which resulted in the following error:

conversion from untyped int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

I have also tried to replace string(math.MaxInt32) with fmt.Sprint(math.MaxInt32), but got another error :

"the maximum int value is " + fmt.Sprint(math.MaxInt32) is not a constant

And the same with strconv.Itoi(math.MaxInt32)

And from my search, I understood that an output from a function is not considered a constant. So is there any way at all to concatenate constant string & constant int while STILL store the result in constant?

1 Answers

If you want to make it a constant, you would need to precalculate the value:

package main

const (
   maxInt32 = "2147483647"
   reportMsg = "the maximum int value is " + maxInt32
)

func main() {
   println(reportMsg)
}
Related