Hello,
I’m new one on Mojo.
How to pass one function pointer(address or name) as a parameter in another function?
When I checked doc, only an example to show pass class method as function parameter.
How about pure function ?
Hello,
I’m new one on Mojo.
How to pass one function pointer(address or name) as a parameter in another function?
When I checked doc, only an example to show pass class method as function parameter.
How about pure function ?
Hi @RobertD,
A standalone function should be passable in the same way as a struct method. Would you like to prove an example of what you tried and what has not worked out?
Hello Samufi,
Thanks for your reply.
For example:
def add(val_1: Int, val_2: Int) → Int:
return vaL_1 + val_2
def sub(val_1: Int, val_2: Int) → Int:
return vaL_1 - val_2
I want to have a function oper, it can be used as below:
oper(add, 12, 23)
oper(sub, 35, 12)
How to declare the function of oper is Mojo?
In c, it might be like below:
int oper(int (*f)(int, int), int val_1, int val_2) {
return f(val_1, val_2);
}
For a detailed description of that, please have a look here: Mojo Closures 2026
In your case, you can pass the function as a parameter (rather than an argument):
def oper[f: def(Int, Int) thin -> Int](val_1: Int, val_2: Int) -> Int:
return f(val_1, val_2)
One hint: on the Mojo Discord, there is an AI bot channel where you can find answers to such questions quite quickly.