ReasonJun

Solidity : Immutable / Constant 본문

Blockchain/Solidity

Solidity : Immutable / Constant

ReasonJun 2023. 10. 16. 21:14
728x90

Immutable and constant are two keywords that can be used to declare variables in Solidity. Both keywords can be used to prevent the value of a variable from being changed, but they have some key differences.

 

Constant variables are initialized at compile time and their value cannot be changed afterwards. This means that constant variables can only be assigned a value once, and they cannot be reassigned or modified thereafter.

 

Immutable variables can be initialized at compile time or at runtime, but their value cannot be changed once it has been set. This means that immutable variables can be assigned a value once, and they cannot be reassigned or modified thereafter.

 

One key difference between constant and immutable variables is that constant variables can be used in constant expressions, while immutable variables cannot. A constant expression is an expression that can be evaluated at compile time.

 

Another key difference between constant and immutable variables is that constant variables can be used in mappings, while immutable variables cannot. Mappings are data structures that store key-value pairs.

 

Here are some examples of how to use constant and immutable variables in Solidity:

// Constant variables
constant uint256 public MAX_SUPPLY = 1000000;

// Immutable variables
immutable uint256 public myNumber;

constructor() {
  myNumber = 10;
}

In the above example, the MAX_SUPPLY variable is a constant variable. This means that its value cannot be changed after it has been initialized. The myNumber variable is an immutable variable. This means that its value cannot be changed after it has been set in the constructor.

 

Constant and immutable variables can be used to make Solidity code more secure and reliable. By using constant and immutable variables, developers can ensure that the values of certain variables cannot be changed accidentally or maliciously.

Here are some tips for using constant and immutable variables in Solidity:

  • Use constant and immutable variables for values that should not change, such as the maximum supply of a token or the address of a contract owner.
  • Use constant and immutable variables in functions that need to read a value, but do not need to change it.
  • Use constant and immutable variables in mappings to improve the security and efficiency of your code.

By following these tips, developers can use constant and immutable variables to make their Solidity code more secure, reliable, and efficient.

728x90

'Blockchain > Solidity' 카테고리의 다른 글

Solidity: Encapsulation  (0) 2023.10.16
Solidity : Inheritance (is, override / Multiple)  (0) 2023.10.16
Solidity : constructor  (0) 2023.10.16
Solidity : Event  (0) 2023.10.16
Solidity : array example  (0) 2023.10.16
Comments