Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method through a function pointer? [duplicate]

What is the correct syntax to call a method on an object using a function pointer?

struct Foo {
    var: i32,
}

impl Foo {
    fn method(&mut self, arg: i32) {
        self.var = self.var + arg;
        println!("var = {}", self.var);
    }
}

fn main() {
    let foo = Foo { var: 11 };
    let func_ptr: Fn() = &foo.method;
    (func_ptr).method(12);
}

I am getting this error:

error[E0615]: attempted to take value of method `method` on type `Foo`
  --> src/main.rs:14:31
   |
14 |     let func_ptr: Fn() = &foo.method;
   |                               ^^^^^^ help: use parentheses to call the method: `method(...)`

error[E0599]: no method named `method` found for type `dyn std::ops::Fn()` in the current scope
  --> src/main.rs:15:16
   |
15 |     (func_ptr).method(12);
   |                ^^^^^^
   |
   = note: (func_ptr) is a function, perhaps you wish to call it

error[E0277]: the size for values of type `dyn std::ops::Fn()` cannot be known at compilation time
  --> src/main.rs:14:9
   |
14 |     let func_ptr: Fn() = &foo.method;
   |         ^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `dyn std::ops::Fn()`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = note: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature

I guess I am not using correct type for func_ptr type; what is the correct type?

like image 766
Nulik Avatar asked Aug 30 '25 17:08

Nulik


1 Answers

Methods do not bind the self argument, but you can get access to the methods via their fully qualified names and you can save them in a function pointer if you like. Later on, when you invoke the function pointer you have to provide the self argument yourself:

struct Foo {
    var: i32,
}

impl Foo {
    fn method(&mut self, value: i32) {
        self.var += value;
        println!("var = {}", self.var);
    }
}

fn main() {
    let mut foo = Foo { var: 11 };
    let func_ptr = Foo::method;
    func_ptr(&mut foo, 12);
}

If you'd like to manually define the type of this local variable then it would be the following:

let func_ptr: fn(&mut Foo, i32) = Foo::method;

If you'd like to use the trait notation, you have to use it behind a reference:

let func_ptr: &Fn(&mut Foo, i32) = &Foo::method;
like image 52
Peter Varo Avatar answered Sep 02 '25 19:09

Peter Varo