为什么两个不同的宏函数在 Nim 中共享变量命名空间?

Why two different macros functions share variable namespace in Nim?

由于 let a 变量的重新声明,下面的代码无法编译。

但是,如果第二个 test 模板被注释掉,它就可以工作了。

为什么会这样,如何解决?

playground

template test*(name: string, body) =
  block: body

template test*(name: string, group: string, body) =
  block: body

test "a1":
  let a = 1

test "a2":
  let a = 1

The body argument to the first template gets typechecked as there is an overload on it where there is a typed argument in the same place. I think your best option for now is to remove the : string annotation on group. To fix this Nim needs to alter its overload semantics in a case like this where it's obvious the arities don't match, but that might be unpredictable.

感谢 hlaaftanaGitHub Issue

中提供答案

所以固定代码为:

template test*(name: string, body) =
  block: body

template test*(name: string, group, body) =
  block: body

test "a1":
  let a = 1

test "a2":
  let a = 1