参数化函数
使用 [方括号] 参数专门化函数
参数化函数 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Functions With a Parameter
A parameterized function takes a compile-time value in square brackets, letting one definition adapt itself before the program runs. ⚙️
fn repeat[count: Int](msg: String):
for i in range(count):
print(msg)The Bracket List
Place your parameters in brackets right after the function name, then your normal arguments in parentheses just after that.
fn scale[factor: Int](x: Int) -> Int:
return x * factorCalling With a Parameter
At the call site you fill the bracket with a constant, then pass runtime arguments in parentheses as usual.
var y = scale[10](4)Each Value Makes a Version
Mojo builds a fresh specialized copy of the function for each parameter value you use, each one tuned exactly for that constant.
Type Parameters
A parameter can even be a type. This is how you write one function that works for Int, Float, or any type you choose.
fn first[T: AnyType](value: T) -> T:
return valueGeneric With Traits
Constrain a type parameter with a trait so the body can safely use the methods that trait promises every conforming type has.
fn show[T: Stringable](value: T):
print(String(value))The Compiler Inlines It
Because the parameter is a constant, the compiler can fold it directly into the code, often removing loops or branches entirely.
Mixing Parameters and Arguments
One function can take both: a compile-time parameter for structure and runtime arguments for the actual data it processes.
fn fill[n: Int](value: Int):
for i in range(n):
print(value)Inferred Parameters
Sometimes Mojo can infer a parameter from the arguments, so you write less and the compiler fills in the rest for you.
Why It Stays Fast
Each specialization is its own optimized function with no runtime cost for the parameter, which is the heart of Mojo's speed.
One Source, Many Builds
You maintain a single readable definition, and the compiler quietly produces many fast, specialized builds behind the scenes.
Quick Check
Recall how a parameterized function is written.
Recap
You wrote parameterized functions: brackets hold compile-time values, the compiler specializes each version, and one source becomes many fast builds. 🎯
常见问题解答
「参数化函数」课时是免费的吗?
是的 — 「参数化函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。
「参数化函数」这节课中我会学到什么?
使用 [方括号] 参数专门化函数 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Mojo Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「参数化函数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Mojo Academy 课中编写并运行代码吗?
能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。