0

basically trying to store methods into a vector, And even mutable methods as the next step to my question. Read some other answers, but those were for closures.

fn main(){}

struct FruitStore{
    fruit:String,
}

impl FruitStore{

    pub fn calculate(&self){

        let mut x:Vec<fn()> = vec![];
        x.push(&self.get_fruit);
    }

    pub fn get_fruit(&self){
        self.fruit;
    }


}```

Compiling playground v0.0.1 (/playground)
error[E0615]: attempted to take value of method `get_fruit` on type `&FruitStore`
  --> src/main.rs:21:22
   |
21 |         x.push(&self.get_fruit);
   |                      ^^^^^^^^^ method, not a field
   |
help: use parentheses to call the method
   |
21 |         x.push(&self.get_fruit());
ender maz
  • 15
  • 4
  • The functions all need to be the same "shape" and you can use `Box B>`. I don't think putting anything with `self` into a `Box` is going to make the borrow checker happy, though. – erip Aug 27 '22 at 00:23

1 Answers1

2

The type in the Vec was wrong. Here is a corrected compiling version:

fn main(){}
struct FruitStore{
    fruit:String,
}
impl FruitStore{
    pub fn calculate(&self){
        let mut x:Vec<fn(&Self)->()> = vec![];
        x.push(FruitStore::get_fruit);
    }
    pub fn get_fruit(&self){
        self.fruit.clone();
    }
}
  • Thank you, but I'm getting into trouble once I add some parameters to `get_fruit(&self, size_height:i32)` – ender maz Aug 27 '22 at 01:45
  • OK, it worked ` let mut x:Vec< &dyn Fn(&Self,i32) -> ()> = vec![]; x.push(&MyStateMachine::get_fruit);` – ender maz Aug 27 '22 at 02:00
  • this answer helped me as well : https://stackoverflow.com/questions/36390665/how-do-you-pass-a-rust-function-as-a-parameter – ender maz Aug 27 '22 at 03:30