Files
pplus-library/mojo/corpus/manual/snippets/manual-parameters-index-1.mojo
alexm 568474d52f
Test (in pplus-core) / in-core (push) Failing after 28m44s
Initial commit
2026-11-12 22:23:48 -05:00

62 lines
1.9 KiB
Mojo
Generated

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")