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



基本上是尝试将方法存储到向量中,甚至将可变方法作为我问题的下一步。阅读其他一些答案,但这些都是针对闭包的。

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

Vec中的类型错误。这是一个更正的编译版本:

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

最新更新