<分区>
我看到了一些相关问题(例如 this 和 this ),但我希望我的默认方法用例足够独特,可以问一个稍微不同的问题。以下最小示例有效并输出 "Sheriff Ted"shot "Billy the Kid"!
:
#[derive(Debug)]
struct Actor {
name: String,
}
fn main() {
let cop = Actor {
name: String::from("Sheriff Ted"),
};
let robber = Actor {
name: String::from("Billy the Kid")
};
println!("{:?} shot {:?}!", cop.name, robber.name); // without the trait. with:
// cop.shoot(&robber);
}
//pub trait Shoot {
// fn shoot(&self, other: &Actor) {
// println!("\n{:?} shot {:?}!",
// &self.name,
// &other.name,
// )
// }
//}
//
//impl Shoot for Actor {}
如您所见,我想将 Shoot
实现及其包含的 shoot
方法传递给 Actor
结构。当我取消注释 Shoot
特性、它在 Actor
上的实现以及调用 cop.shoot(&robber)
时,我得到了与错误消息相关的问题还有:error[E0609]: no field 'name' on type '&Self'
。
我的第一个想法是在默认方法的签名中指定 &self: Actor
,但这会产生定界符错误,因此在语法上是无效的。
我认为这个问题很独特,因为其他问题似乎误解了它们指定的泛型如何影响它们的预期类型,在我的例子中,我不明白为什么我不能访问我所在的结构中的字段尝试实现默认方法。
这适用于只有 Actor
需要 shoot
的情况,但我正在寻找一种应用此行为的方法(现在,只是 println
ing) 跨多种类型。
impl Actor {
fn shoot(&self, other: &Actor) {
println!("\n{:?} shot {:?}!",
self.name,
other.name,
)
}
}