我编写了一个程序,它具有特征Animal和Dog实现特征的结构.它还有一个AnimalHouse存储动物作为特征对象的结构Box<Animal>.
trait Animal {
fn speak(&self);
}
struct Dog {
name: String,
}
impl Dog {
fn new(name: &str) -> Dog {
return Dog {
name: name.to_string(),
};
}
}
impl Animal for Dog {
fn speak(&self) {
println!{"{}: ruff, ruff!", self.name};
}
}
struct AnimalHouse {
animal: Box<Animal>,
}
fn main() {
let house = AnimalHouse {
animal: Box::new(Dog::new("Bobby")),
};
house.animal.speak();
}
Run Code Online (Sandbox Code Playgroud)
它返回"Bobby:ruff,ruff!" 正如所料,但如果我尝试克隆house编译器返回错误:
fn main() {
let house …Run Code Online (Sandbox Code Playgroud) 甲FnMut闭合无法克隆,出于显而易见的原因,但Fn封闭件具有一个不可变的范围; 有没有办法创建一个Fn闭包的"重复" ?
尝试克隆它会导致:
error[E0599]: no method named `clone` found for type `std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send + 'static>` in the current scope
--> src/main.rs:22:25
|
22 | fp: self.fp.clone(),
| ^^^^^
|
= note: self.fp is a function, perhaps you wish to call it
= note: the method `clone` exists but the following trait bounds were not satisfied:
`std::boxed::Box<std::ops::Fn(i8, i8) -> i8 + std::marker::Send> : std::clone::Clone`
Run Code Online (Sandbox Code Playgroud)
以某种方式将原始指针传递给Fn周围是安全的,例如:
let func_pnt = …Run Code Online (Sandbox Code Playgroud) 我有一个结构,其中一个字段是一个函数指针.我想实现该Clone结构的特征,但我不能,因为如果它们至少有一个参数,则无法克隆函数指针:
fn my_fn(s: &str) {
println!("in my_fn {}", s);
}
type TypeFn = fn(s: &str);
#[derive(Clone)]
struct MyStruct {
field: TypeFn
}
fn main() {
let my_var = MyStruct{field: my_fn};
let _ = my_var.clone();
}
Run Code Online (Sandbox Code Playgroud)