我试图将结构中函数的HashMap设置为结构中的字段,并像下面的代码一样调用它们。但是它有编译错误。我该如何修复?
main.rs
use std::collections::HashMap;
struct A{
pub funcs: HashMap<&'static str, fn()->()>,
f1:i32,
f2:i32
}
impl A {
fn func1(&mut self) {self.f1+=1;println!("func1 has called {} time(s)",self.f1);}
fn func2(&mut self) {self.f2+=1;println!("func2 has called {} time(s)",self.f2);}
fn set_funcs(&mut self) {
self.funcs = HashMap::from([("f1",Self::func1),("f2",Self::func2)]);
}
}
fn main() {
let mut a = A{funcs:HashMap::new(),f1:0,f2:0};
a.set_funcs();
a.funcs.get("f1").unwrap()();
}
编译错误
error[E0308]: mismatched types
--> src/main.rs:12:58
|
12 | self.funcs = HashMap::from([("f1",Self::func1),("f2",Self::func2)]);
| ^^^^^^^^^^^ expected fn item, found a different fn item
|
= note: expected fn item `for<'r> fn(&'r mut A) {A::func1}`
found fn item `for<'r> fn(&'r mut A) {A::func2}`
error[E0308]: mismatched types
--> src/main.rs:12:18
|
12 | self.funcs = HashMap::from([("f1",Self::func1),("f2",Self::func2)]);
| ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found fn item
| |
| expected due to the type of this binding
|
= note: expected struct `HashMap<&'static str, fn()>`
found struct `HashMap<&str, for<'r> fn(&'r mut A) {A::func1}>`
函数有一个参数:&mut self
。self
的类型为Self
/A
。A::func1
是fn(&mut A) -> ()
不是fn() -> ()
use std::collections::HashMap;
struct A{
pub funcs: HashMap<&'static str, fn(&mut Self)->()>,
f1:i32,
f2:i32
}
impl A {
fn func1(&mut self) {self.f1+=1;println!("func1 has called {} time(s)",self.f1);}
fn func2(&mut self) {self.f2+=1;println!("func2 has called {} time(s)",self.f2);}
fn set_funcs(&mut self) {
self.funcs.insert("f1", Self::func1);
self.funcs.insert("f2", Self::func2);
}
}
fn main() {
let mut a = A{funcs:HashMap::new(),f1:0,f2:0};
a.set_funcs();
a.funcs.get("f1").unwrap()(&mut a);
}