So I'm relatively new to nim, and have been using generics to great effects. Really enjoying the experience so far. Now I wanted to do something different depending on the type parameter, like this:
proc createMyArray*(N: static[int]): array[N, int] =
if N == 2:
result = [1, 2]
if N == 3:
result = [1, 2, 3]
which results in errors like this Error: type mismatch: got <array[0..1, int]> but expected 'array[0..2, int]'. Which makes sense, no matter what I plug in for N, one of the result lines does not have the correct syntax. So I thought using templates might help:
proc createMyArray*(N: static[int]): array[N, int] =
template choice(N: static[int]): untyped =
if N == 2:
result = [1, 2]
if N == 3:
result = [1, 2, 3]
choice(N)
which unfortunately results in the same error. I have tried adding static and const at various points, but realized I had no idea what I was doing and should rather ask. So how do I do this?Hi! Welcome to the Nim community :) The error in your case is pretty simple - you need to use when instead of if to make different branches based on a compile-time value, like so:
proc createMyArray*(N: static[int]): array[N, int] =
when N == 2:
result = [1, 2]
elif N == 3:
result = [1, 2, 3]
echo createMyArray(2)
echo createMyArray(3)
See https://nim-lang.org/docs/manual.html#statements-and-expressions-when-statement
if is strictly runtime, you need to use when in this case:
proc createMyArray*(N: static[int]): array[N, int] =
when N == 2:
result = [1, 2]
elif N == 3:
result = [1, 2, 3]