简体   繁体   English

将结构的方法存储到向量中

[英]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());

The type in the Vec was wrong. Vec中的类型错误。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM