首页 > 解决方案 > 来自 proc 的隐式返回值

问题描述

这里的 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

标签: nim-lang

解决方案


在您的divmodprocremainder = 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

如果您真的不需要修改现有值,这就是您可以重新制作 proc 的方式:

proc divmod(a, b: int): (int, int) =
  (a div b, a mod b)

let (x, y) = divmod(8, 5)

echo x, " ", y

推荐阅读