我如何避免消耗传递给' impl Trait '参数的值?



如何将值传递给以impl Trait为参数的函数后保持其所有权?我试过传递参数作为参考,没有&,但它们都不起作用。

trait Noise{
fn make_noise(&self);
fn call_by_name(&self);
}
struct Person {
name: String,
}
impl Noise for Person{
fn make_noise(&self){
println!("Hello");
}
fn call_by_name(&self) {
println!("Hey, {:?}, how are you doing?", self.name)
}
}
fn talk(noisy: impl Noise){
noisy.make_noise();
}
fn main() {
let john_person = Person { name: String::from("John") };
talk(john_person); 
john_person.call_by_name(); // ERROR WHEN CALLING THE FUNCTION.
}

你应该让fn talk通过引用而不是通过值来获取trait对象:

trait Noise {
fn make_noise(&self);
fn call_by_name(&self);
}
struct Person {
name: String,
}
impl Noise for Person {
fn make_noise(&self) {
println!("Hello");
}
fn call_by_name(&self) {
println!("Hey, {:?}, how are you doing?", self.name)
}
}
fn talk(noisy: &impl Noise) {  // <- used &impl Noise
noisy.make_noise();
}
fn main() {
let john_person = Person {
name: String::from("John"),
};
talk(&john_person);           // call by reference, not move
john_person.call_by_name();
}

否则,将john_person移动到功能talk。这意味着你不能再访问它了。

如果你通过引用传递它,它将被借用,直到函数结束。

最新更新