Web3 & DApp Development Fundamentals · 课时

常量与不可变变量

节省 Gas 的值

第 4 / 4 课13 个步骤

常量与不可变变量 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Fixed Values Save Gas

Some values never change after a contract is deployed. For these, Solidity offers constant and immutable keywords that store the value in the contract bytecode instead of expensive storage slots.

Using them reduces gas and signals intent to readers.

Declaring Constants

A constant must be assigned at the point of declaration and known at compile time. Its value can never change.

By convention constants use UPPER_CASE names.

<code>uint256 public constant MAX_SUPPLY = 1000000;
string public constant NAME = 'MyToken';</code>

How Constants Work

A constant does not occupy a storage slot. The compiler inlines its value everywhere it is used, so reading it costs almost nothing.

This makes constants ideal for configuration like decimals, caps, and fixed fees.

<code>uint8 public constant DECIMALS = 18;

function unit() public pure returns (uint256) {
    return 10 ** DECIMALS; // inlined at compile time
}</code>

Declaring Immutables

An immutable variable is set once, either at declaration or in the constructor, and then can never change.

Unlike constants, its value can depend on runtime data such as deployment arguments.

<code>address public immutable owner;

constructor() {
    owner = msg.sender; // set at deploy time
}</code>

Constant vs Immutable

The key difference is when the value is fixed:

  • constant - fixed at compile time, must be a literal expression
  • immutable - fixed at deploy time, can use constructor inputs

Both are stored in bytecode, not in storage slots.

Immutable with Constructor Args

Immutables shine when each deployment needs different fixed parameters, like a token's total supply or an associated contract address.

<code>uint256 public immutable cap;

constructor(uint256 _cap) {
    cap = _cap; // unique per deployment
}</code>

Gas Savings

Reading a regular state variable requires an SLOAD (storage read), which is costly. Constants and immutables are read directly from bytecode, which is far cheaper.

Converting frequently-read fixed config to constant/immutable is an easy optimization.

<code>// Expensive: storage read each call
uint256 public feeStorage = 100;

// Cheap: read from bytecode
uint256 public constant FEE = 100;</code>

What Cannot Be Constant

A constant cannot depend on anything computed at runtime. Values like block.timestamp, msg.sender, or storage reads are forbidden for constants.

For those, use immutable instead.

<code>// ERROR: not compile-time known
// uint256 constant T = block.timestamp;

// OK as immutable
uint256 immutable deployedAt;
constructor() { deployedAt = block.timestamp; }</code>

Immutables Are Read-Only

After the constructor finishes, an immutable can never be reassigned. Any attempt to write to it outside the constructor is a compile error.

<code>address public immutable factory;
constructor(address f) { factory = f; }

function change(address x) public {
    // factory = x; // ERROR: cannot assign
}</code>

Common Use Cases

Typical patterns:

  • constant for token decimals, max supply caps, and fixed fee rates
  • immutable for the owner, deployment timestamp, and linked contract addresses

Both improve clarity and reduce gas compared to mutable state.

<code>uint8 public constant DECIMALS = 18;
address public immutable deployer;
constructor() { deployer = msg.sender; }</code>

Naming Convention

By widespread convention, constant names are written in UPPER_SNAKE_CASE, while immutable names often use normal camelCase or a leading underscore for constructor params.

Consistent naming makes audits faster.

<code>uint256 public constant MAX_HOLDERS = 500;
address public immutable treasury;</code>

Quick Check

Test your understanding of constants and immutables.

Recap

You learned about gas-efficient fixed values:

  • constant - compile-time literal, inlined into bytecode, UPPER_CASE
  • immutable - set once at deploy time (often in the constructor), then read-only
  • Both avoid expensive storage reads (SLOAD)

Use constants for known literals and immutables for per-deployment configuration.

免费开始

用 AI 导师学习 Web3 & DApp Development Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
29
课程
105

常见问题解答

「常量与不可变变量」课时是免费的吗?

是的 — 「常量与不可变变量」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「常量与不可变变量」这节课中我会学到什么?

节省 Gas 的值 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「常量与不可变变量」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 值类型
  2. 引用类型
  3. 存储与内存
  4. 常量与不可变变量
← 返回 Web3 & DApp Development Fundamentals