@parameter
You can add the @parameter decorator on a nested function to create a
parametric closure.
Parametric closureโ
You can add @parameter on a nested function to create a "parametric"
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()3Note 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 captured by the parametric closure. This allows the compiler to correctly extend the lifetimes of those values. For more information on lifetimes and origins, see Lifetimes, origins and references.
If you leave the @parameter decorator off the add() function above, you'll
get a compiler error:
invalid call to 'use_closure': failed to infer parameter '__origins__'Parametric if statementโ
The @parameter if syntax is deprecated, please use comptime if instead.
For more information, see the section on
compile-time conditionals.
Parametric for statementโ
The @parameter for syntax is deprecated, please use comptime for instead.
For details, see the section on
compile-time loop unrolling.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!