pub 函数与可见性
让函数能够跨文件使用。
pub 函数与可见性 是 CoddyKit 上的免费 Zig Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Zig Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Zig Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Files Are Modules
In Zig every source file is its own module. What it shares with other files is controlled by visibility rules. 📦
Private by Default
A plain function is private to its file. Other files cannot call it, which keeps internal helpers safely hidden.
fn helper() void {
// only this file can call me
}pub Makes It Public
Add the pub keyword to expose a function so other files can import and call it across your project.
pub fn greet() void {
std.debug.print("Hi!\n", .{});
}Import Brings It In
Another file uses @import to load your module, then reaches public names through the returned value.
const utils = @import("utils.zig");
utils.greet();Only pub Names Are Reachable
Through that import you can call only the public names. Private functions stay invisible, so they cannot be misused.
Why main Needs pub
This is why main is written pub: the runtime lives outside your file and must be able to reach the entry point.
pub Works on More Than fn
The pub keyword also exposes constants, types, and variables, letting you publish a clean public surface for a module.
pub const version = "1.0.0";Design a Small API
Mark only what callers truly need as public. Keeping helpers private gives you a small, stable interface to maintain.
Encapsulation Reduces Bugs
Hiding internals is encapsulation. With fewer exposed parts, you can change implementation details without breaking other files.
No Headers Needed
Unlike C, Zig needs no header files. Importing a file gives you its public declarations directly, with no duplication.
Visibility Is Compile-Time
Zig enforces visibility at compile time. Calling a private function from outside its file simply fails to compile.
Quick Check
You wrote a function in math.zig and another file cannot call it. What is most likely missing?
Recap
Functions are private to their file until you add pub. Expose only what callers need, import with @import, and skip headers entirely. 🎯
常见问题解答
「pub 函数与可见性」课时是免费的吗?
是的 — 「pub 函数与可见性」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Zig Academy 课程的其余内容,请升级到 CoddyKit PRO。 Zig Academy 课程共包含 4 节课。
「pub 函数与可见性」这节课中我会学到什么?
让函数能够跨文件使用。 你通过在浏览器中直接运行的动手代码来练习 Zig Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Zig Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Zig Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「pub 函数与可见性」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Zig Academy 课中编写并运行代码吗?
能。每节 Zig Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。