I was solving some exercises to get some practice in go and came across the following problem.
Take this function:
func foo(s string) {
length := len(s);
// Do something just reading from lenght
}
Here, thanks to programing in other languages, my mind immediately went "length will not be modified, so it should be marked const".
So I did this:
const length = len(s);
But it gives me the following error:
const initializer len(s) is not a constant
I suppose that is because len(s)
cant be calculated "at compile time" (Not
sure if this is 100% correct talking about go).
Is there any way to indicate that length
should not be modified? I searched
in Google, but I found nothing usefull. I got some thins about immutable structs, but
I think its too complex for what I want to do.
len(s)
cannot be calculated at compile time becauses
is a variable. If the mutable variable bothers you, then uselen(s)
directly instead of declaring a variable.