Nim: _ (underscore) is not ignored inside templates

Created on 30 Mar 2020  路  4Comments  路  Source: nim-lang/Nim

Example

  1. _ gets gensym'd if used as a variable name:
template foo() =
  let _ = 3

foo()
  1. _ is substituted if used as a parameter name for the template
template foo(_: int) =
  for _ in 1..3: # Error: identifier expected, but found '4'
    echo "hello"

foo(4)

Current Output

1.

(2, 7) Hint: '_`gensym133006' is declared but not used [XDeclaredButNotUsed]

2.

(5, 5) Error: identifier expected, but found '4'

Expected Output

doesn't warn or error, correctly does not gensym in the first case, and does not try to substitute in the second case

Workaround

template foo() =
  let _ {.inject.} = 3

foo()
$ nim -v
Nim Compiler Version 1.2.6

Most helpful comment

template foo =
  let (_, a, b) = (3, 4, 5)

warns when unpacking a tuple

All 4 comments

What's the use case though? Your example should use discard.

template foo =
  let (_, a, b) = (3, 4, 5)

warns when unpacking a tuple

When 2 "_" are used in tuple unpacking in a template, it generate compile error.

#No compile error
let (_, _, x) = (1, 2, 3)
echo x

template test() =
  #Error: redefinition of '_`gensym3387051'; previous declaration here: f:\temp\testTU.nim(5, 8)
  let (_, _, x) = (1, 2, 3)
  echo x

test()

Just ran into this bug again, but in a different way. Not only do templates not ignore _, they also try to substitute with it if it's the name of a parameter.

template foo(_: int) =
  for _ in 1..3: # Error: identifier expected, but found '4'
    echo "hello"

foo(4)
Was this page helpful?
0 / 5 - 0 ratings