一个Mech
搭载了一个驾驶员,这是一个Named
实体。在运行时,省略的Mech
构造函数会向外部资源查询要使用的具体驾驶员类型。
trait Named {
fn name(self) -> String;
}
struct Person {
first_name: String,
last_name: String
}
impl Named for Person {
fn name(self) -> String {
format!("{} {}", self.first_name, self.last_name)
}
}
pub struct Mech<'a> {
driver: Box<Named + 'a>,
}
impl<'a> Mech<'a> {
pub fn driver_name(self) -> String {
self.driver.name()
}
}
driver_name
方法将所有权返回到String
,以便在链接调用中进一步使用(在实际代码中它是一个Command
)。如果编译失败,则会出现以下情况:
error[E0161]: cannot move a value of type Named + 'a: the size of Named + 'a cannot be statically determined
--> src/lib.rs:22:9
|
22 | self.driver.name()
| ^^^^^^^^^^^
使特征
Sized
失败的对象安全性:trait Named: Sized {
fn name(self) -> String;
}
↓
error[E0038]: the trait `Named` cannot be made into an object
--> src/lib.rs:17:5
|
17 | driver: Box<Named + 'a>,
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Named` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`
有没有办法实现这个模式?
我是否缺少了什么基本的东西?
如果无法实现,有什么好的解决方法?
self
而不是&self
? - Shepmasterfn take_name(&mut self) -> String
是对象安全的,但需要对类型的状态域进行扩展。 - E net4