运算符可能会陷入推断类型。纳特元子

operator may trap for inferred type. Motoko Nat

我已经编写了这个简单的 Motoko 代码,但是当我部署我的容器时,我收到一条警告,指出 operator 可能会捕获推断类型。奈特元子


    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")
        }
        
      };
    }

我正在使用 candid UI 来调用我的函数,我的代码工作正常但我无法摆脱警告,任何人都可以帮助我,如何删除警告

在下图中,错误指的是行:

let tempValue = currentValue - amount;

因为减法 currentValue - amount 的两个操作数都是 Nat 类型,所以减法是在 Nat 类型上执行的。这意味着如果结果变为负数,结果将超出范围,并且您会陷入陷阱。永远不会达到下一行的测试。所以警告是有原因的。 :)

(编辑:FWIW,警告实际上是“operator may trap for inferred type Nat”,它只是在 Candid 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;