0Pricing
Zig Academy · 课时

传递值与传递引用

了解参数如何传入您的函数。

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

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

How Arguments Travel

When you call a function, Zig must get your data inside it. There are two routes: pass the value itself or pass a reference to it. 🚚

Passing by Value Copies

By default, primitive arguments are passed by value: the function gets its own copy and cannot change your original.

fn addOne(n: i32) i32 {
    return n + 1;
}

Copies Stay Independent

Because it is a copy, edits inside the function never touch the caller. Your variable outside stays exactly as it was.

Parameters Are Immutable

Function parameters in Zig are immutable. You cannot reassign a parameter inside the body, which keeps intent clear.

Pass a Pointer to Share

To let a function change your data, pass a pointer with *T. The function then works on your actual value, not a copy.

fn bump(n: *i32) void {
    n.* += 1;
}

Dereference to Reach It

Inside, you use .* to read or write through the pointer. n.* += 1 updates the value the caller still holds.

Take the Address with &

At the call site you pass an address using &. Then bump(&count) lets the function modify count in place.

var count: i32 = 0;
bump(&count); // count is now 1

Big Data Prefers References

For large structs, copying is wasteful. Passing a const pointer shares the data cheaply without allowing changes.

fn area(r: *const Rect) i32 {
    return r.w * r.h;
}

const Pointer Means Read-Only

A *const T lets the function read your data but never write it. You get speed without giving up safety.

Slices Are Already Views

A slice like []const u8 carries a pointer plus a length, so passing it shares the underlying data without a full copy.

Choose Based on Intent

Pass by value for small, read-only data; pass a pointer when you must mutate or when the data is large.

Quick Check

You want a function to change the caller variable. Which parameter form lets it do that?

Recap

Values are copied and cannot change your originals; pointers share them. Use *T to mutate and *const T to read large data fast. 🎯

常见问题解答

「传递值与传递引用」课时是免费的吗?

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

「传递值与传递引用」这节课中我会学到什么?

了解参数如何传入您的函数。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Zig Academy 需要有经验吗?

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

「传递值与传递引用」课时需要多长时间?

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

我能在这节 Zig Academy 课中编写并运行代码吗?

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

此课程中的所有课时

  1. 函数语法与返回类型
  2. 传递值与传递引用
  3. pub 函数与可见性
  4. 递归与多返回值
← 返回 Zig Academy