作为语句和表达式的 if
用同一种形式进行分支并返回值。
作为语句和表达式的 if 是 CoddyKit 上的免费 Zig Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Zig Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Zig Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Branching with if
Use if to choose between paths. Zig runs the first block when the condition is true and skips it otherwise. Simple and explicit. 🌿
if (score > 50) {
std.debug.print("Pass\n", .{});
}Conditions Must Be bool
The condition in parentheses must be a real bool. Zig refuses integers or pointers here, so there is no truthy-or-falsy guessing.
Adding an else
Pair if with else to handle the false case. Exactly one of the two blocks runs, never both and never neither.
if (ready) {
start();
} else {
wait();
}Chaining else if
Stack tests with else if to pick one branch from several. Zig checks them top to bottom and stops at the first match.
if (n < 0) {
sign = -1;
} else if (n > 0) {
sign = 1;
} else {
sign = 0;
}if Is an Expression
In Zig, if can also produce a value. Both branches return something, and the whole if becomes that result you can assign.
const max = if (a > b) a else b;Both Branches Must Match
When if yields a value, both arms must share one type. The compiler reconciles them so the result has a single, predictable type.
No Ternary Needed
Zig has no ternary operator. The expression form of if fills that role cleanly, keeping just one way to write a choice.
Unwrapping an Optional
An if can test and unwrap an optional in one move. The captured name holds the inner value only when it is present.
if (maybe_user) |user| {
greet(user);
}Capturing Errors with if
An if can also peel apart an error union. The else branch can capture the error value when the expression fails.
if (parse(text)) |value| {
use(value);
} else |err| {
report(err);
}Braces Are Required
Zig always needs braces around if bodies, even for a single line. This removes a whole class of dangling-statement bugs.
Returning Early
A common pattern is an early return inside an if. Handle the special case first, then let the rest of the function read straight down.
if (list.len == 0) return;Quick Check
You want max to hold the larger of a and b in one line. Which Zig form works?
Recap
You met if as both a statement and an expression: bool conditions, else and else if, value-returning branches, and optional or error capturing. 🎯
常见问题解答
「作为语句和表达式的 if」课时是免费的吗?
是的 — 「作为语句和表达式的 if」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Zig Academy 课程的其余内容,请升级到 CoddyKit PRO。 Zig Academy 课程共包含 4 节课。
「作为语句和表达式的 if」这节课中我会学到什么?
用同一种形式进行分支并返回值。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Zig Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Zig Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「作为语句和表达式的 if」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Zig Academy 课中编写并运行代码吗?
能。每节 Zig Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。