如需获取本内容的最新版本,请参见 Cyfrin.io 上的Variables(代码示例)
Solidity 中有三种类型的变量:
- local 局部变量
- 在函数内部声明
- 不在区块链上存储
- state 状态变量
- 在函数外部声明
- 存储在区块链上
- global 全部变量
- 提供区块链信息
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract Variables {
// 状态变量存储在区块链上
string public text = "Hello";
uint256 public num = 123;
function doSomething() public view {
// 局部变量不存储在链上,只存在函数体中
uint256 i = 456;
// 以下为全局变量
uint256 timestamp = block.timestamp; // 当前区块时间戳
address sender = msg.sender; // 调用者地址
}
}
Remix Lite 尝试一下
END