使用可变的varargs在NIM中无法正常工作

发布于 2025-02-02 16:07:40 字数 543 浏览 3 评论 0原文

试图制定一个简单的过程来修改NIM中的一个可变数量的参数(例如,从输入初始化许多变量)。

proc Read(outputVars: var varargs[int]) =
    for v in outputVars.mitems:
        v = 3

var
    a, b, c : int

Read(a, b, c)

但是,编译器不喜欢这种编译器并输出:

Error: type mismatch: got <int, int, int>
but expected one of:
proc Read(outputVars: var varargs[int])
  first type mismatch at position: 1
  required type for outputVars: var varargs[int]
  but expression 'a' is of type: int
  
expression: Read(a, b, c)

如何制作一个程序来接受可变数量的可变参数?

trying to make a simple procedure to modify a variable number of arguments in nim (for example to initialize a number of a variables from input).

proc Read(outputVars: var varargs[int]) =
    for v in outputVars.mitems:
        v = 3

var
    a, b, c : int

Read(a, b, c)

However the compiler doesn't like this and outputs:

Error: type mismatch: got <int, int, int>
but expected one of:
proc Read(outputVars: var varargs[int])
  first type mismatch at position: 1
  required type for outputVars: var varargs[int]
  but expression 'a' is of type: int
  
expression: Read(a, b, c)

How can I make a procedure that accepts a variable number of mutable arguments?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ˇ宁静的妩媚 2025-02-09 16:07:40

之所以不起作用,是因为varargs是引擎盖下的数组。即使可能是可变的,这些值仍然必须复制到数组中,因此更新它们也不会更新原始变量。

IMO表达您的示例的正确“安全”方法将是varargs [var int],即向整数的一系列可变视图。但这也不起作用,因为nim's /a>功能仍然是实验性的。

工作的一个不太安全的解决方案,正在使用a 胁迫varargs 指向整数的指针。例如:

proc varIntAddr(n: var int): ptr int =
  addr n

proc read(outputVars: varargs[ptr int, varIntAddr]) =
  for v in outputVars:
    v[] = 3

var a, b, c: int

read(a, b, c)

echo (a, b, c)

在这里,如果您传递了可变的整数,varintaddr将被隐式地应用于他们,以将其地址添加到数组中。

您也可以像这样一概而论:

proc varAddr[T](n: var T): ptr T =
  addr n

The reason this doesn't work is because varargs is an array under the hood. Even if it could be mutable, the values would still have to be copied into the array, so updating them wouldn't update the original variables.

IMO the correct "safe" way to express your example would be something like varargs[var int], i.e. an array of mutable views to integers. But this also doesn't work because Nim's views feature is still experimental.

A less safe solution which does work, is using a coercing varargs of pointers to integers. For example:

proc varIntAddr(n: var int): ptr int =
  addr n

proc read(outputVars: varargs[ptr int, varIntAddr]) =
  for v in outputVars:
    v[] = 3

var a, b, c: int

read(a, b, c)

echo (a, b, c)

Here if you pass in mutable integers, varIntAddr will be implicitly applied to them to take their addresses which get added to the array.

You can also generalise the proc like so:

proc varAddr[T](n: var T): ptr T =
  addr n
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文