Search code examples
goconstantsimmutability

How to declare an immutable variable in Go?


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.


Solution

  • You cannot specify a variable to be immutable. Only constants have this property.

    Constants in Go are also compile-time constant, meaning you can't initialize it to something that depends on the particular value of some variable like s in your example.

    Also, with rare exceptions, functions cannot return constants. Even when they can, it must still be a compile-time constant. len can return a constant value, but only if the parameter is constantly sized, such as a string constant or of an array type (which has fixed length in Go).