Search code examples
nim-lang

Why referring to immutable variable is NOT side effect free in Nim?


The code below won't compile because of the reference to the let one = 1.

Why? It seems like it's side effect free (and thread safe too) - as it's impossible to change the immutable data.

playground

let one = 1
func one_plus(v: int): int =
  one + v
  
echo one_plus(2)

Does code like that - referring to external immutable data - supposed to be written somehow differently in Nim to be considered side-effect free?


Solution

  • My guess is the problem is using the global namespace, wrapping your code into a proc makes it compile and run:

    proc main() =
      let one = 1
      func one_plus(v: int): int =
        one + v
        
      echo one_plus(2)
    
    main()
    

    If you still want to use a global, you need to use const section:

    const one = 1
    func one_plus(v: int): int =
      one + v
      
    echo one_plus(2)