Skip to main content

三种类型变量-常量-读取写入状态变量

1.Solidity中有3种类型的变量

  • 当地的
    • 在函数内部声明
    • 不存储在区块链上
  • 状态
    • 在函数外部声明
    • 存储在区块链上
  • 全球(提供有关区块链的信息)

There are 3 types of variables in Solidity local declared inside a function not stored on the blockchain

state declared outside a function stored on the blockchain global (provides information about the blockchain)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Variables {
// State variables are stored on the blockchain.
string public text = "Hello";
uint public num = 123;

function doSomething() public {
// Local variables are not saved to the blockchain.
uint i = 456;

// Here are some global variables
uint timestamp = block.timestamp; // Current block timestamp
address sender = msg.sender; // address of the caller
}
}

2.常量:不能修改的变量

它们的值是硬编码的,使用常量可以节省天然气成本。

Constants are variables that cannot be modified.

Their value is hard coded and using constants can save gas cost.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Constants {
// coding convention to uppercase constant variables
address public constant MY_ADDRESS = 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc;
uint public constant MY_UINT = 123;
}

3.读取和写入状态变量

要写入或更新状态变量,您需要发送交易。

另一方面,您可以免费读取状态变量,无需任何交易费用。

To write or update a state variable you need to send a transaction.

On the other hand, you can read state variables, for free, without any transaction fee.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

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