首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符可能会捕获推断类型。莫托科·纳特

运算符可能会捕获推断类型。莫托科·纳特
EN

Stack Overflow用户
提问于 2022-05-07 13:54:54
回答 1查看 111关注 0票数 0

我已经编写了这个简单的Motoko代码,但是当我部署我的罐时,我会收到一个警告,说明操作符可能会捕获推断类型。莫托科·纳特

代码语言:javascript
复制
    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;

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-07 14:53:39

由于减法currentValue - amount的两个操作数都是Nat类型,所以减法在Nat类型下执行。这意味着,如果结果变成负值,结果就会超出界限,你就会得到一个陷阱。下一行的测试永远也达不到。所以这个警告是有原因的。:)

(编辑: FWIW,该警告实际上是“操作符可能陷阱推断类型Nat",它只是奇怪地包装在坦率的UI中。)

我建议将该功能改为:

代码语言:javascript
复制
      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类型执行减法:

代码语言:javascript
复制
let tempValue : Int = currentValue - amount;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72153174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档