使用可变的varargs在NIM中无法正常工作
试图制定一个简单的过程来修改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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
之所以不起作用,是因为
varargs
是引擎盖下的数组。即使可能是可变的,这些值仍然必须复制到数组中,因此更新它们也不会更新原始变量。IMO表达您的示例的正确“安全”方法将是
varargs [var int]
,即向整数的一系列可变视图。但这也不起作用,因为nim's /a>功能仍然是实验性的。工作的一个不太安全的解决方案,正在使用a 胁迫varargs 指向整数的指针。例如:
在这里,如果您传递了可变的整数,
varintaddr
将被隐式地应用于他们,以将其地址添加到数组中。您也可以像这样一概而论:
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:
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: