我已经编写了这个简单的Motoko代码,但是当我部署我的罐时,我会收到一个警告,说明操作符可能会捕获推断类型。莫托科·纳特
import Debug "mo:base/Debug";
actor DBank {
var currentValue = 300;
currentValue := 100;
public func topUp(amount: Nat) {
currentValue += amount;
Debug.print(debug_show(currentValue));
};
public func withdraw(amount:Nat) {
let tempValue = currentValue - amount;
if(tempValue>=0) {
currentValue -= amount;
Debug.print(debug_show(currentValue));
} else {
Debug.print("amount too large, not enough balance")
}
};
}我使用直截了当的UI来调用我的函数,我的代码运行良好,但我无法消除警告,有人能帮我吗,如何删除警告
在下面的图像中,错误指的是行:
设tempValue = currentValue - amount;

发布于 2022-05-07 14:53:39
由于减法currentValue - amount的两个操作数都是Nat类型,所以减法在Nat类型下执行。这意味着,如果结果变成负值,结果就会超出界限,你就会得到一个陷阱。下一行的测试永远也达不到。所以这个警告是有原因的。:)
(编辑: FWIW,该警告实际上是“操作符可能陷阱推断类型Nat",它只是奇怪地包装在坦率的UI中。)
我建议将该功能改为:
public func withdraw(amount : Nat) {
if (amount <= currentValue) {
currentValue -= amount;
Debug.print(debug_show(currentValue));
} else {
Debug.print("amount too large, not enough balance");
}
};编辑2:另一种解决方案是通过添加类型注释来强制Int类型执行减法:
let tempValue : Int = currentValue - amount;https://stackoverflow.com/questions/72153174
复制相似问题