# Solidity 课程 14: 常量 **Published by:** [Novar](https://paragraph.com/@novar/) **Published on:** 2022-06-08 **URL:** https://paragraph.com/@novar/solidity-14 ## Content 合约的状态变量可以声明为不可变常数,数值定义后不能再次编辑,可以节约gas fee。有两种定义命令,constant 和 immutable ,区别是constant只支持值类型和字符串,immutable可以;constant必须声明时就赋值,immutable可以推迟到构造函数里赋值 。举例: //1、constant只支持值类型和字符串,immutable可以; address public constant MY_ADDRESS = 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc; uint public constant MY_UINT = 123; string public constant MY_STRING = "123"; bytes public constant MY_BYTES = "123"; address public immutable MY_ADDRESS_IM = 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc; uint public immutable MY_UINT_IM = 123; // string public immutable MY_STRING_IM = 123; //bytes public immutable MY_BYTES = "123"; //2、constant必须声明时就赋值,immutable可以推迟到构造函数里赋值 uint public immutable MY_UINT_CONSTRUCTOR; uint256 public immutable IMMUTABLE_TEST; constructor(){ MY_UINT_CONSTRUCTOR = 123; IMMUTABLE_TEST = test(); } function test() public pure returns(uint256){ uint256 what = 9; return(what); } 这节学习了不可变常量的两种定义方式,constant 和 immutable,可以节约gas fee。Code:https://github.com/Luca-Hsu/SuperSolidity/blob/main/14_Constants/Constants.solReference:https://solidity-by-example.org/constants https://solidity-by-example.org/immutable https://docs.soliditylang.org/en/v0.8.4/contracts.html#constant-and-immutable-state-variables ## Publication Information - [Novar](https://paragraph.com/@novar/): Publication homepage - [All Posts](https://paragraph.com/@novar/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@novar): Subscribe to updates