【发布时间】:2019-04-14 16:24:01
【问题描述】:
我看到了一些相关的问题(如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 实现和它包含在Actor 结构上的shoot 方法传授给它。当我取消注释Shoot 特征、它在Actor 上的实现以及调用cop.shoot(&robber) 时,我也收到了与问题相关的错误消息:error[E0609]: no field 'name' on type '&Self'。
我的第一个想法是在默认方法的签名中指定&self: Actor,但这会产生分隔符错误,因此在语法上无效。
我认为这个问题是独一无二的,因为其他问题似乎误解了他们指定的泛型如何影响他们的预期类型,就我而言,我不明白为什么我不能访问我所在的结构中的字段尝试实现默认方法。
这适用于只有 Actors 需要 shoot 的情况,但我正在寻找一种方法来跨多种类型应用此行为(现在,只需 printlning)。
impl Actor {
fn shoot(&self, other: &Actor) {
println!("\n{:?} shot {:?}!",
self.name,
other.name,
)
}
}
【问题讨论】:
-
我相信Is it possible to access struct fields from within a trait?的答案已经回答了您的问题。如果您不同意,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。
-
@Shepmaster 我在问题顶部引用的那些答案都没有明确说明(无论如何对我而言)结构字段无法从默认方法定义访问,因为错误假设struct 将具有该字段(仍然在探索如何使用绑定来确保使用具有所述字段的结构类型)。试图在下面的回答中找到这种区别。如果我错了,那么我们可以标记为骗子。编辑:我现在看到了,
default implementation of a trait (i.e. defining a method body within the trait), then no, you can't access fields. -
回复也很好,here:
A trait cannot expose a field/attribute...(cont)