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:

  1. proc myWriteln(f: File, a: varargs[string]) =
  2. for s in items(a):
  3. write(f, s)
  4. write(f, "\n")
  5. myWriteln(stdout, "abc", "def", "xyz")
  6. # is transformed to:
  7. myWriteln(stdout, ["abc", "def", "xyz"])

This transformation is only done if the varargs parameter is the last parameter in the procedure header. It is also possible to perform type conversions in this context:

  1. proc myWriteln(f: File, a: varargs[string, `$`]) =
  2. for s in items(a):
  3. write(f, s)
  4. write(f, "\n")
  5. myWriteln(stdout, 123, "abc", 4.0)
  6. # is transformed to:
  7. myWriteln(stdout, [$123, $"abc", $4.0])

In this example $ is applied to any argument that is passed to the parameter a. (Note that $ applied to strings is a nop.)

Note that an explicit array constructor passed to a varargs parameter is not wrapped in another implicit array construction:

  1. proc takeV[T](a: varargs[T]) = discard
  2. takeV([123, 2, 1]) # takeV's T is "int", not "array of int"

varargs[typed] is treated specially: It matches a variable list of arguments of arbitrary type but always constructs an implicit array. This is required so that the builtin echo proc does what is expected:

  1. proc echo*(x: varargs[typed, `$`]) {...}
  2. echo @[1, 2, 3]
  3. # prints "@[1, 2, 3]" and not "123"