用于演示此行为的简单程序:
use std::boxed::Box;
struct Cow;
trait CanSpeak {
fn speak(&self);
}
impl CanSpeak for Cow {
fn speak(&self) {
println!("moo");
}
}
impl<F: Fn()> CanSpeak for F {
fn speak(&self) {
self();
}
}
impl<T: CanSpeak> CanSpeak for Box<T> {
fn speak(&self) {
(**self).speak()
}
}
fn lol_speak() {
println!("lol")
}
fn lets_speak<T: CanSpeak>(t: & T) {
t.speak();
}
fn main() {
let cow = Cow;
lets_speak( &cow );
lets_speak( &lol_speak );
let boxed_cow = Box::new(Cow);
lets_speak( &boxed_cow );
}
编译失败:
test.rs:15:1: 19:2 error: conflicting implementations for trait `CanSpeak` [E0119]
test.rs:15 impl<F: Fn()> CanSpeak for F {
test.rs:16 fn speak(&self) {
test.rs:17 self();
test.rs:18 }
test.rs:19 }
test.rs:15:1: 19:2 help: run `rustc --explain E0119` to see a detailed explanation
test.rs:21:1: 25:2 note: note conflicting implementation here
test.rs:21 impl<T: CanSpeak> CanSpeak for Box<T> {
test.rs:22 fn speak(&self) {
test.rs:23 (**self).speak()
test.rs:24 }
test.rs:25 }
error: aborting due to previous error
我的问题是:
Box<T>
未实现Fn()
特征。那么为什么上面的例子失败了?我刚开始学习Rust。谢谢你的帮助。
答案 0 :(得分:6)
这两者之间存在冲突,因为类型Box<T>
可能让T
实施CanSpeak
和Box<T>
实施{{1} }}。 Rust一致性规则不是关于是的内容,而是可以。
以下是为Fn()
实施Fn()
的示例,如果它允许您的两个通用特征实现,它会明显爆炸:
Box<Cow>