I converted a golang code snippet from https://go.dev/blog/loopvar-preview to nim.
var prints: seq[proc ()] = @[]
for i in 1..3:
prints.add(proc () = echo i)
for print in prints:
print()
This code currently prints 3, 3, 3. How do I modify the code so that the output would be 1, 2, 3?Great job on converting the Go code to Nim! To modify the Nim code so that it prints 1, 2, 3, you can capture the value of i for each iteration using a temporary variable. Here's the modified code:
nim Copy code var prints: seq[proc ()] = @[]
By introducing the tmp variable and capturing the value of i within each iteration, you ensure that each closure in the prints sequence has its own copy of i, resulting in the desired output of 1, 2, 3.