Assume we have a proc like this (it doesn't do anything sensible):
proc coolProc[T](x: openArray[T]): T =
when x.len == 1:
echo "Nothing to see! Move on!"
else:
echo "How have you gotten " & x.len & "gold coins already?!"
Let's say I call it using this code:
coolProc(@[0])
coolProc(@[0, 1, 2])
Is there multiple versions of coolProc created for all the "when-scenarios" or is there just one (if we ignore that it's generic)? In other words, would this code give me the expected results?
temp.nim(7, 9) template/generic instantiation of `coolProc` from here
temp.nim(2, 8) Error: cannot evaluate at compile time: x
😅🤦 hehe...
Is there any cases where a when-statement can be used in a proc?
@hugogranstrom Your example cannot work because x.len == 0 cannot be evaluated at compile time since x could be some data coming from user input, file input, etc.
But to answer you more general question about how when statements work, no they do not generate alternate versions. They operate somewhat like a #ifdef function in C. The code that is under the true branch will be included in the AST and compiled, and the code in the false branch will be excluded from the AST and will not exist in the final binary output.