I see some related questions (like this and this) but I'm hoping that my use case for default methods is unique enough to ask a slightly different question. The following minimal example works and outputs "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 {}
As you can see, I want impart the Shoot
implementation and the shoot
method it contains on the Actor
struct. When I uncomment the Shoot
trait, its implementation on Actor
, and the call cop.shoot(&robber)
, I get the error message related questions have gotten, as well: error[E0609]: no field 'name' on type '&Self'
.
My first thought was to specify &self: Actor
in the default method's signature, but that yields the delimiter error, so isn't syntactically valid.
I think this question is unique because the other questions seem to misunderstand how the generics they specify are shadowing their intended types, and in my case I'm not understanding why I can't access fields within the structs on which I am trying to implement a default method.
This works for cases when only Actor
s need to shoot
, but I am looking for a way to apply this behavior (right now, just println
ing) across multiple types.
impl Actor {
fn shoot(&self, other: &Actor) {
println!("\n{:?} shot {:?}!",
self.name,
other.name,
)
}
}