How to declare an immutable variable in Go?

Viewed 1927

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.

2 Answers

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).

For something with similar result, you could use a private field. Make a module like this:

package foo

type Length struct { value int }

func NewLength(s string) Length {
   return Length{
      len(s),
   }
}

func (l Length) Int() int { return l.value }

then use like this:

package main
import "foo"

func main() {
   l := foo.NewLength("north")
   println(l.Int() == 5)
   // l.value undefined (cannot refer to unexported field or method value)
   l.value = 6
}
Related