Recently, I have been revisiting Solidity, consolidating the finer details, and writing "WTF Solidity" tutorials for newbies.
Twitter: @0xAA_Science | @WTFAcademy_
Community: Discord|Wechat|Website wtf.academy
Codes and tutorials are open source on GitHub: github.com/AmazingAng/WTF-Solidity
In this section, we will introduce two keywords to restrict modifications to their state in Solidity: constant and immutable. If a state variable is declared with constant or immutable, its value cannot be modified after contract compilation.
Value-typed variables can be declared as constant and immutable; string and bytes can be declared as constant, but not immutable.
constant and immutable
constant
The constant variable must be initialized during declaration and cannot be changed afterwards. Any modification attempt will result in an error at compilation.
Immutable
The immutable variable can be initialized during declaration or in the constructor, which is more flexible.
You can initialize the immutable variable using a global variable such as address(this), block.number, or a custom function. In the following example, we use the test() function to initialize the IMMUTABLE_TEST variable to a value of 9:
Verify on Remix
-
After the contract is deployed, You can obtain the values of the
constantandimmutablevariables through thegetterfunction.
-
After the
constantvariable is initialized, any attempt to change its value will result. In the example, the compiler throws:TypeError: Cannot assign to a constant variable.
-
After the
immutablevariable is initialized, any attempt to change its value will result. In the example, the compiler throws:TypeError: Immutable state variable already initialized.
Summary
In this section, we introduced two keywords to restrict modifications to their state in Solidity: constant and immutable. They keep the variables that should not be changed unchanged. It will help to save gas while improving the contract's security.