6

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.

3
  • 3
    There is no way to define an immutable variable in go. You can define constants, but the value must be evaluated at compile time, hence you cannot do len(s) where s is a variable Commented Jun 21, 2021 at 21:48
  • 2
    len(s) cannot be calculated at compile time because s is a variable. If the mutable variable bothers you, then use len(s) directly instead of declaring a variable. Commented Jun 21, 2021 at 21:48
  • 3
    The nature of a "variable" is that it is variable.
    – Volker
    Commented Jun 22, 2021 at 5:26

2 Answers 2

11

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

2

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.