第7节:读写状态变量

小白入门:https://github.com/dukedaily/solidity-expert ,欢迎star转发,文末加V入群。

职场进阶: https://dukeweb3.com

  1. 写状态变量(上链)是一笔交易(tx),需要矿工打包,所以需要花费资金;
  2. 读取状态变量,是从账本中获取数据,不是一笔交易,所以免费。(必须加上view)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract SimpleStorage {
    // State variable to store a number
    uint public num;

    // You need to send a transaction to write to a state variable.
    function set(uint _num) public {
        num = _num;
    }

    // You can read from a state variable without sending a transaction.
    function get() public view returns (uint) {
        return num;
    }
}