Immutable and Constant
Using the
constant
and theimmutable
keywords for variables that do not change helps to save on gas used.constant
andimmutable
variables do not occupy a storage slot when compiled.They are saved inside the contract byte code.
What is a constant variable?
A constant variable in Solidity is a variable whose value cannot be changed once set. This means that a constant variable can only be assigned a value once, and it cannot be reassigned or modified thereafter.
assignment has to be done at declaration
What is an immutable variable?
An immutable variable in Solidity refers to a variable whose reference cannot be changed. In other words, an immutable variable is a variable that points to an object, and the object’s value cannot be changed, but the variable can be reassigned to point to a new object.
For example, if you have an immutable variable named “y” that points to a string “Hello”, you cannot change the string to “Goodbye”, but you can reassign “y” to point to a new string “Hola”.
Values of immutable variables can be set inside the constructor but cannot be modified afterward.
Constants are typically used when you want to ensure that a value cannot be changed, while immutables are used when you want to ensure that a reference cannot be changed.
Last updated