这里的 nim lang教程说 -
没有任何 return 语句且不使用特殊结果变量的过程返回其最后一个表达式的值。
为什么我的echo res打印 0 ?我不应该期望a mod b返回最后一个语句(= 3) 吗?
proc divmod(a, b: int; res, remainder: var int): int =
res = a div b
remainder = a mod b
var
x, y: int
let res: int = divmod(8, 5, x, y) # modifies x and y
echo res
Run Code Online (Sandbox Code Playgroud)
在您的divmodproc 中remainder = a mod b是一个语句,而不是一个表达式,因此 divmod 返回 int 的默认值为 0。
我不确定你为什么要通过可变参数和结果返回余数,但这是你可以做到的:
proc divmod(a, b: int; res, remainder: var int): int =
res = a div b
remainder = a mod b
remainder # or result = remainder
var
x, y: int
let res: int = divmod(8, 5, x, y) # modifies x and y
echo res
Run Code Online (Sandbox Code Playgroud)
如果您真的不需要修改现有值,这就是您可以重新制作 proc 的方式:
proc divmod(a, b: int): (int, int) =
(a div b, a mod b)
let (x, y) = divmod(8, 5)
echo x, " ", y
Run Code Online (Sandbox Code Playgroud)