This commit is contained in:
commit
568474d52f
1591 files changed
+528213
No files matched your search
@@ -0,0 +1,61 @@
|
||||
def multiplier[factor: Int](x: Int) -> Int:
|
||||
return x * factor
|
||||
|
||||
|
||||
def main():
|
||||
comptime times_ten = multiplier[10]
|
||||
var x10 = times_ten(3)
|
||||
```
|
||||
|
||||
Parameters accept both types and values at compile time. When a
|
||||
parameter accepts a type, the result is type-parameterized code. When it
|
||||
accepts a value, the result is value-parameterized code.
|
||||
|
||||
```mojo no-test
|
||||
struct MyList[T: AnyType]:
|
||||
# ... type-parameterized
|
||||
|
||||
struct FixedBuffer[size: Int]:
|
||||
# ... value-parameterized
|
||||
```
|
||||
|
||||
Mojo's parameters are similar to C++ template parameters or Rust generic
|
||||
parameters.
|
||||
|
||||
In Mojo, "parameter" always means a compile-time value, and
|
||||
"argument" always means a run-time value.
|
||||
|
||||
In most other languages, a parameter is part of a declaration and an
|
||||
argument is the value you pass at the call site. Mojo changes the
|
||||
meaning of "parameter" to refer specifically to compile-time values.
|
||||
|
||||
Mojo makes this distinction visible in syntax: use `[]` for
|
||||
parameters and `()` for arguments.
|
||||
|
||||
In addition to parameterizing structs and functions, you can also define
|
||||
parameterized `comptime` values.
|
||||
|
||||
## Parameterized functions {#parameters-and-generics}
|
||||
|
||||
To define a *parameterized function*, add parameters in square brackets ahead
|
||||
of the argument list. Each parameter is formatted just like an argument: a
|
||||
parameter name, followed by a colon and a type. In the
|
||||
following example, the function has a single parameter, `count` of type `Int`.
|
||||
|
||||
```mojo
|
||||
def repeat[count: Int](msg: String):
|
||||
comptime for i in range(count):
|
||||
print(msg)
|
||||
```
|
||||
|
||||
The [`comptime`](/docs/manual/metaprogramming/comptime-evaluation/#comptime-for)
|
||||
keyword shown here
|
||||
causes the `for` loop to be fully unrolled at compile time. The `comptime for`
|
||||
requires the loop limits to be known at compile time. Since `count` is a
|
||||
parameter, `range(count)` can be calculated at compile time.
|
||||
|
||||
Calling a parameterized function, you provide values for the parameters, just
|
||||
like function arguments:
|
||||
|
||||
```mojo
|
||||
repeat[3]("Hello")
|
||||
Reference in new issue
Block a user