使用 if 和 orelse 安全解包
在没有意外的情况下处理 null。
使用 if 和 orelse 安全解包 是 CoddyKit 上的免费 Zig Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Zig Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Zig Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
You Must Unwrap First
An optional is not the value inside it. Before you can use the contents you have to unwrap it and deal with the null case.
Capture with if
An if on an optional can bind the inner value with a pipe capture. The body runs only when the optional is not null.
if (maybe) |value| {
use(value);
}Handle the null Branch
Add an else to react when the optional is null. Now both outcomes are covered with no chance of a missing case.
if (maybe) |v| {
use(v);
} else {
handleEmpty();
}The Capture Is Unwrapped
Inside the if body the captured name is the plain inner type, not an optional. The question mark is already gone for you.
if (age) |a| {
// a is i32, not ?i32
}orelse Supplies a Default
The orelse operator unwraps an optional, but if it is null it gives back the value on its right instead.
const a = age orelse 0;orelse Is an Expression
Because orelse returns a value, you can use it inline anywhere, like passing a defaulted number straight into a function call.
print(level orelse 1);orelse Can Run Code
The right side of orelse may be a block. Use it to compute a fallback or even return early from the current function.
const v = lookup() orelse return;Force Unwrap with .?
Writing .? asserts the optional is not null and hands back the value. If it is null in a safe build, your program panics.
const a = age.?;Use .? Only When Certain
Reach for .? only when null is truly impossible. Otherwise prefer if or orelse so an empty value never crashes you.
Choose by Intent
Use if to branch on presence, orelse for a quick default, and .? only when you can prove the value is there.
Safety Is the Default
Each tool forces you to acknowledge null. That is why Zig optionals rarely turn into the surprise crashes seen in other languages.
Quick Check
You want a default of 0 when an optional integer is null. Which fits best?
Recap
You can unwrap optionals with if captures, supply defaults via orelse, or assert with .?. Each one makes you face null on purpose. ✅
常见问题解答
「使用 if 和 orelse 安全解包」课时是免费的吗?
是的 — 「使用 if 和 orelse 安全解包」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Zig Academy 课程的其余内容,请升级到 CoddyKit PRO。 Zig Academy 课程共包含 4 节课。
「使用 if 和 orelse 安全解包」这节课中我会学到什么?
在没有意外的情况下处理 null。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Zig Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Zig Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 if 和 orelse 安全解包」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Zig Academy 课中编写并运行代码吗?
能。每节 Zig Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 声明可选类型
- 使用 if 和 orelse 安全解包
- 可选指针与 ?*T
- null 与 undefined 的区别