I try to understand
Warning: Special variable 'result' is shadowed. [ResultShadowed]
in following code:
import math
proc toNumArray(n: int): array[6, int] =
var n = n
var result = [0, 0, 0, 0, 0, 0]
for i in 0..<6:
result[5-i] = trunc(float(n mod 10)).int
n = n div 10
result
echo toNumArray(123456)
I know shadowing is used, because parameter are immutable. So I got some questions about shadowing
Nothing wrong with n.
All proc and func have an automatic result variable created from the type on the signature of the function.
Change var result = to result =
As @juancarlospaco said, Nim has an implicitly declared result variable. It is zero like all variables zero initialised and returned by default which is great to remove some boilerplate code:
import math
proc toNumArray(n: int): array[6, int] =
var n = n
for i in 0..<6:
result[5-i] = trunc(float(n mod 10)).int
n = n div 10
echo toNumArray(123456)
See also: https://nim-lang.org/docs/manual.html#statements-and-expressions-return-statement