【发布时间】:2016-06-01 04:21:47
【问题描述】:
我有两个结构,VM 和 Word。我需要一个新的结构Control,它的行为就像VM,但多了一个字段master。因为 Rust 没有继承,所以我尝试通过组合来扩展结构。我将VM 的功能移动到一个新的特征Core 中,并为Control 实现Core。生成的代码有效。
struct Word<T> {
action: fn(target: &T)
}
struct VM {
word: Word<VM>
}
trait Core<T> {
fn word(&self) -> &Word<T>;
fn hello(&self) { println!("Hello"); }
fn execute(&self);
}
impl Core<VM> for VM {
fn word(&self) -> &Word<VM> { &self.word }
fn execute(&self) { (self.word().action)(self); }
}
struct Control {
word: Word<Control>,
master: i32,
}
impl Core<Control> for Control {
fn word(&self) -> &Word<Control> { &self.word }
fn execute(&self) { (self.word().action)(self); }
}
fn main() {
let vm = VM{
word: Word {action: Core::hello}
};
vm.execute();
let control = Control{
word: Word {action: Core::hello},
master: 0,
};
vm.execute();
}
execute 的两个实现是相同的。所以我将 execute 移动到 trait Core。
trait Core<T> {
fn word(&self) -> &Word<T>;
fn hello(&self) { println!("Hello"); }
fn execute(&self) { (self.word().action)(self); }
}
impl Core<VM> for VM {
fn word(&self) -> &Word<VM> { &self.word }
}
impl Core<Control> for Control {
fn word(&self) -> &Word<Control> { &self.word }
}
编译时出现以下错误:
main.rs:14:44: 14:48 error: mismatched types:
expected `&T`,
found `&Self`
(expected type parameter,
found Self) [E0308]
main.rs:14 fn execute(&self) { (self.word().action)(self); }
我该如何解决这个问题?
【问题讨论】:
-
感谢您纠正我糟糕的英语。
标签: rust