Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a function pointer to a method in Rust?

Tags:

rust

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()` 
like image 389
Vortico Avatar asked Jul 14 '14 01:07

Vortico


People also ask

Does Rust have function pointers?

In Rust, a function pointer type, is either fn(Args...)

What is FN in Rust?

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.

How to return closures in Rust?

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.

Is it normal to register a rust function with function pointers?

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.

How do I work with raw pointers in rust?

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.

How to call a rust function from a Rhai script?

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.

How do I create a function pointer using FN?

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:


1 Answers

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(); 
like image 161
huon Avatar answered Sep 21 '22 20:09

huon