header-langage
简体中文
English
Tiếng Việt
Scan to Download the APP
Partnered With:

A minimalist introduction to Solidity|Lecture 9: Constants and immutables

Read this article in 4 Minutes
This article introduces two keywords in solidity, constant (constant) and immutable (invariant), so that variables that should not change remain unchanged.
Original title: "Introduction to Solidity Minimalist: 9. Constants constant and immutable"
Original author: 0xAA  


< p>I am re-learning solidity recently, to consolidate the details, and also write an "Introduction to Solidity Minimalist" for novices to use (programmers can find another tutorial), and update 1-3 lectures every week.


All codes and tutorials are open source on github: github.com/AmazingAng/WTFSolidity


Here In the first lecture, we introduce two keywords in solidity, constant (constant) and immutable (invariant). After the state variable declares these two keywords, the value cannot be changed after the contract; and it can also save gas. Also, only numeric variables can be declared constant and immutable; String and bytes can be declared constant, but not immutable.


constant and immutableconstant


constant 


< /p>

Variables must be initialized when they are declared and cannot be changed afterwards. If you try to change it, the compilation will fail.



immutable


Immutable variables can be initialized at declaration time or in the constructor, so they are more flexible.



You can use global variables such as address(this), block.number , or custom functions to initialize immutable variables. In the following example, we use the test() function to initialize IMMUTABLE_TEST to 9:  


< p style="text-align:center;">


Summary


In this lecture, we introduce two keywords in solidity, constant (constant) and immutable (invariant), so that variables that should not change remain unchanged.


Original link


Welcome to join the official BlockBeats community:

Telegram Subscription Group: https://t.me/theblockbeats

Telegram Discussion Group: https://t.me/BlockBeats_App

Official Twitter Account: https://twitter.com/BlockBeatsAsia

举报 Correction/Report
Choose Library
Add Library
Cancel
Finish
Add Library
Visible to myself only
Public
Save
Correction/Report
Submit