【问题标题】:Why is it not possible to reassign the value in the contract level in solidity?为什么无法在solidity中重新分配合约级别的值?
【发布时间】:2021-12-04 08:24:28
【问题描述】:

这是我的代码, 我想知道我无法更改变量 a 中的值的原因。 能否请您告诉我原因或来自solidity doc的任何信息?

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

contract simple {
    uint public a = 3;
    a = 16; // error occurred : parser Error expected identifier but got '='
    }

【问题讨论】:

标签: blockchain ethereum solidity ether


【解决方案1】:

您正在尝试更改合约代码的声明部分中的数据。将更改放入合约构造函数或函数中。

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

contract simple
{
    uint public a = 3;

    constructor()
    {
      a = 16; 
    }

    function changeData() public
    {
      a = 16;
    }

}

【讨论】:

    【解决方案2】:

    您需要合约中的函数来修改值。您可以通过将函数声明为view 类型来实现此目的。例如

    contract Demo {
    
        uint number;
    
        function set(uint _number) public {
            number = _number + 1;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2021-07-25
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      相关资源
      最近更新 更多