For example,
struct Foo; impl Foo { fn bar(&self) {} fn baz(&self) {} } fn main() { let foo = Foo; let callback = foo.bar; }
error[E0615]: attempted to take value of method `bar` on type `Foo` --> src/main.rs:10:24 | 10 | let callback = foo.bar; | ^^^ help: use parentheses to call the method: `bar()`
In Rust, a function pointer type, is either fn(Args...)
Keyword fnFunctions are the primary way code is executed within Rust. Function blocks, usually just called functions, can be defined in a variety of different places and be assigned many different attributes and modifiers.
Closures are represented by traits, which means you can't return closures directly. In most cases where you might want to return a trait, you can instead use the concrete type that implements the trait as the return value of the function.
It is completely normal to register a Rust function with an Engine that takes parameters whose types are function pointers. The Rust type in question is rhai::FnPtr. A function pointer in Rhai is essentially syntactic sugar wrapping the name of a function to call in script.
Working with raw pointers in Rust is uncommon, typically limited to a few patterns. Use the null and null_mut functions to create null pointers, and the is_null method of the *const T and *mut T types to check for null.
The Rust type in question is rhai::FnPtr. A function pointer in Rhai is essentially syntactic sugar wrapping the name of a function to call in script. Therefore, the script’s execution context is needed in order to call a function pointer. The type NativeCallContext holds the native call context of the particular call to a registered Rust function.
A function pointer is created via the Fn function, which takes a string parameter. Call a function pointer using the call method. The following standard methods (mostly defined in the BasicFnPackage but excluded if using a raw Engine) operate on function pointers:
With fully-qualified syntax, Foo::bar
will work, yielding a fn(&Foo) -> ()
(similar to Python).
let callback = Foo::bar; // called like callback(&foo);
However, if you want it with the self
variable already bound (as in, calling callback()
will be the same as calling bar
on the foo
object), then you need to use an explicit closure:
let callback = || foo.bar(); // called like callback();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With