0Pricing
Mojo Academy · 课时

以只读方式借用参数

用于安全读取的默认借用方式

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

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

Why Ownership Matters

When you pass a value to a function, Mojo needs to know who can read or change it. That rule is an ownership convention. 🔑

The Default Is Borrowing

By default an argument is borrowed. The function gets read access to the caller's value but does not take it over.

Read, Don't Modify

A borrowed argument is read-only inside the function. You can look at it freely, but Mojo will not let you change it.

No Copy Needed

Borrowing avoids copying the data. The function shares the caller's value as an immutable reference, which keeps things fast.

Spelling It Out

You can write borrowed before a parameter to be explicit, though it is already the default for an fn function.

fn area(borrowed w: Int, borrowed h: Int) -> Int:
    return w * h

The Same Without the Keyword

Because borrowing is the default, you usually skip the keyword. This function reads its argument exactly the same way.

fn area(w: Int, h: Int) -> Int:
    return w * h

Trying to Mutate Fails

If you assign to a borrowed argument, the compiler stops you. That error is Mojo protecting the caller's value.

Safe to Share

Because the function only reads, you can borrow the same value in many calls at once with no risk of a surprise change.

Great for Big Data

Borrowing shines when a value is large. You read a big struct without paying the cost of a full copy on every call.

Caller Keeps Ownership

After a borrowed call, the original variable is still valid and unchanged. The caller never lost ownership of its value.

The Safe Read Default

Borrowing is Mojo's safe, efficient default: read access, no copy, no mutation. Reach for it whenever a function only needs to inspect data.

Quick Check

Let us test what a borrowed argument allows.

Recap

Borrowing is the default: the function reads the caller's value with no copy and no mutation. It is Mojo's safe, fast way to pass data. 🎯

常见问题解答

「以只读方式借用参数」课时是免费的吗?

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

「以只读方式借用参数」这节课中我会学到什么?

用于安全读取的默认借用方式 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Mojo Academy 需要有经验吗?

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

「以只读方式借用参数」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 以只读方式借用参数
  2. 使用 inout 原地变更
  3. 使用 owned 获取所有权
  4. 转移运算符
← 返回 Mojo Academy