nim-lang - 来自 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
解决方案
在您的divmod
procremainder = 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
推荐阅读
- html - Is there a way to get smooth css keyframes animation?
- typescript - 你能增加枢轴的大小吗?
- swift - 重载相等运算符 (==) 以比较 String 和 Int
- javascript - 将 POST 数据反应到 ASP.Net
- html - 带有用户选择的Div:嵌套在用户选择中时自动不起作用:无
- c# - grpc:所有呼叫都在取消而不打算取消
- java - AllNodesFailedException:无法到达任何联系点
- java - 数据表正在自动添加我不想要的字符
- powershell - 如何将目录列表放入列表框中
- android - 如何在活动中隐藏recyclerview的所有项目