ender maz
ender maz

Reputation: 15

storing methods of a struct into a vector

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());

Upvotes: 0

Views: 615

Answers (1)

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();
    }
}

Upvotes: 2

Related Questions