Files
pplus-core/mojo/corpus/manual/snippets/manual-parameters-index-2.mojo
T
2026-10-05 03:03:38 +00:00

184 lines
6.5 KiB
Mojo

def repeat_3(msg: String):
print(msg)
print(msg)
print(msg)
```
:::note
This doesn't represent actual code generated by the compiler. By the
time parameters are resolved, Mojo code has already been transformed to an
intermediate representation in [MLIR](https://mlir.llvm.org/).
:::
If the compiler can't resolve all parameter values to constant values,
compilation fails.
### Overloading on parameters
Functions and methods can be overloaded on their parameter signatures. For
information on overload resolution, see
[Overloaded functions](/docs/manual/functions/#overloaded-functions).
## Parameters at a glance
Parameters to a function or struct appear in square brackets after a function
or struct name. Parameters always require type annotations.
When you're looking at a function or struct signature, you may
see some special characters such as `/` and `*` in the parameter list.
Here's an example:
```mojo
def my_sort[
# infer-only parameters
dtype: DType,
width: SIMDLength,
//,
# positional-only parameter
values: SIMD[dtype, width],
/,
# positional-or-keyword parameter
compare: def(Scalar[dtype], Scalar[dtype]) thin -> Int,
*,
# keyword-only parameter
reverse: Bool = False,
]() -> SIMD[dtype, width]:
```
Here, `compare` is a function-typed parameter. Because the comparator is a
noncapturing function value, the function type explicitly uses `thin`.
Here's a quick overview of the special characters in the parameter list:
- Double slash (`//`): parameters declared before the double slash are
[infer-only parameters](#infer-only-parameters).
- Slash (`/`): parameters declared before a slash are positional-only
parameters. Positional-only and keyword-only parameters follow the same rules
as [positional-only and keyword-only
arguments](/docs/manual/functions#positional-only-and-keyword-only-arguments).
- A parameter name prefixed with a star, like `*Types` identifies a
[variadic parameter](#variadic-parameters) (not shown in the example above).
Any parameters following the variadic parameter are keyword-only.
- Star (`*`): in a parameter list with no variadic parameter, a star by itself
indicates that the following parameters are keyword-only parameters.
- An equals sign (`=`) introduces a default value for an
[optional parameter](#optional-parameters-and-keyword-parameters).
## Parameterized declarations
Parameterization let functions work across multiple types, and let containers
store values of many types. For example,
[`List`](/docs/std/collections/list/List/) takes a type parameter, so
`List[Int]` holds integers and `List[String]` holds strings.
In Mojo, parameterizations use compile-time elements. A function parameterized
on a type is type-parameterized. A function parameterized on a value is
value-parameterized. Both use `[]`.
This function uses both a type parameter and a value parameter:
```mojo
def repeat[
MsgType: Writable, // infer-only
count: Int
](msg: MsgType):
comptime for _ in range(count):
print(msg)
def main():
repeat[2](42) # prints 42 on two lines
```
`MsgType` is type-parameterized. It accepts any `Writable` type. `count` is
value-parameterized. It accepts a compile-time integer. Together, they let
you write one function that works across types and specializes for
different repeat counts.
`MsgType` uses `//` to mark it as an
[infer-only parameter](#infer-only-parameters). The compiler infers
the type from `msg`, so you only pass `count` explicitly.
For more on parameterized declarations, including trait conformance, conditional
conformance, and value parameterizations, see
[parameterized declarations](/docs/manual/generics/).
## Parameterized structs
You can also add parameters to structs. You can use parameterized structs to
build parameterized collections. For example, a parameterized array type might
include code like this:
```mojo
from std.memory.alloc import alloc, dealloc, ThinAllocation, Layout
struct ParameterizedArray[T: Copyable & Deinitable](
Writable where conforms_to(T, Writable)
):
var _data: ThinAllocation[Self.T]
var _size: Int
def __init__(out self, var *elements: Self.T):
self._size = len(elements)
self._data = alloc[Self.T]({count = self._size}).into_thin()
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_write(elements[i].copy())
def __init__(out self, *, count: Int, value: Self.T):
self._size = count
self._data = alloc[Self.T]({count = count}).into_thin()
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_write(copy=value)
def __deinit__(deinit self):
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_deinit_pointee()
dealloc(self._data^.unsafe_with_layout({count = self._size}))
def __getitem__(self, i: Int) raises -> ref[self] Self.T:
if i < self._size:
return self._data.unsafe_ptr().unsafe_origin_cast[
origin_of(self)
]()[unsafe_offset=i]
else:
raise Error("Out of bounds")
def write_to(
self, mut writer: Some[Writer]
) where conforms_to(Self.T, Writable):
writer.write("[")
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
writer.write(ptr[unsafe_offset=i])
if i < self._size - 1:
writer.write(", ")
writer.write("]")
```
This struct has a single parameter, `T`, which is a placeholder for
the data type you want to store in the array, sometimes called a *type
parameter*. `T` conforms to the
[`Copyable`](/docs/std/traits/copyable/Copyable/) trait and therefore to the
[`Movable`](/docs/std/traits/movable/Movable/) trait.
As with parameterized functions, you need to pass in parameter values when you
use a parameterized struct. In this case, when you create an instance of
`ParameterizedArray`, you need to specify the type you want to store, like
`Int`, or `Float64`. (This is a little confusing, because the *parameter value*
you're passing in this case is a *type*. That's OK: a Mojo type is a valid
compile-time value.)
You'll see that `Self.T` is used throughout the struct where you'd
usually see a type name. For example, as the formal type for the `elements` in
the initializer, and the return type of the `__getitem__()` method.
Here's an example of using `ParameterizedArray`:
```mojo
var array = ParameterizedArray(1, 2, 3)
print(array)