Hi, are mixed typed varargs possible?
https://play.nim-lang.org/#ix=4LTx
proc printThings(args: varargs[string | int]) =
for arg in args:
when arg is string:
echo arg
when arg is int:
echo arg
printThings( "words", "to", "print", 123)
error
>
/opt/homebrew/Cellar/nim/2.0.0_1/nim/lib/system/iterators.nim(11, 17) Error: cannot instantiate: 'T'
Tip: 4 messages have been suppressed, use --verbose to show them.
nimble.nim(229) buildFromDir
https://nim-lang.org/docs/manual.html#types-varargs
A varargs parameter is an open array parameter that additionally allows a variable number of arguments to be passed to a procedure. The compiler converts the list of arguments to an array implicitly
And an array elements can have only one type.
This is my hacky solution to this specific use-case.
template printThings(args: auto) =
for arg in `args`.fields:
echo arg
printThings ("words", "to", "print", 123)
check it out
I ran into this exact issue when I was working on openai Api for nim, so I just gave up and used json to collect variable type input from users 😅
thanks for the replys
template printThings(args: auto) =
for arg in `args`.fields:
echo arg
works but interested in how [typed]
might look likeimport std/macros
macro printThings(x: varargs[typed, `$`]): untyped =
result = newCall("echo", newLit"Mine: ")
for arg in x:
result.add arg
printThings "Hello", [1, 2, 3, 4,], 10, 200, 300, true