IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.0.0
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

@parameter

You can add @parameter on a nested function to create a legacy capturing closure. This means you can create a closure function that captures values from the outer scope (regardless of whether they are variables or parameters), and then use that closure as a parameter. For example:

def use_closure[func: fn(Int) capturing [_] -> Int](num: Int) -> Int:
return func(num)

def create_closure():
var x = 1

@parameter
def add(i: Int) -> Int:
return x + i

var y = use_closure[add](2)
print(y)

create_closure()
3

Note the [_] in the function type:

def use_closure[func: fn(Int) capturing [_] -> Int](num: Int) -> Int:

This origin specifier represents the set of origins for the values that the legacy closure captures. This allows the compiler to correctly extend the lifetimes of those values. For more information on lifetimes and origins, see Lifetimes, origins and references.