定数の定義であるconstantとimmutableとの違いについてメモします。
constant: 値の変更ができない。
immutable: constructor内で値の設定はできるが、その後は値の変更ができない。
なのでRemix IDEだとこちらはエラーになります。
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
contract Sample{
uint public constant number;
constructor(uint _num){
number = _num;
}
}
immutableを用いた場合は、エラーはなくconstructorで値を設定できます。
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
contract Sample{
uint public immutable number;
constructor(uint _num){
number = _num;
}
}
ドキュメントには、constantの値はコンパイラ後には変更できない、immutableの値はコンパイラ後に1度だけ変更できるというニュアンスで記載されています。
コード書く→コンパイラ→デプロイ(constructor実行) という順番なのでそうなりますね。
https://docs.soliditylang.org/en/v0.8.18/contracts.html#constant-and-immutable-state-variables