根据文档,如果我尝试调用由两个不同特征提供的方法,Rust应该抱怨:
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) { println!("Baz’s impl of Foo"); }
}
impl Bar for Baz {
fn f(&self) { println!("Baz’s impl of Bar"); }
}
fn main(){
let b = Baz;
b.f();
}
Run Code Online (Sandbox Code Playgroud)
运行此操作会导致预期的error: multiple applicable methods in scope错误.
但是我没有得到任何错误:
extern crate mio;
use mio::buf::RingBuf;
use mio::buf::Buf;
use std::io::Read;
fn main() {
let buf = RingBuf::new(10);
let bytes = buf.bytes();
println!("{:?}", bytes);
}
Run Code Online (Sandbox Code Playgroud)
mio::buf::RingBuf实现Buf和Read.两种特质都提供了一种bytes方法.
我希望Rust抱怨与上面相同的错误.相反,它默默地选择"错误"的实现,然后println抱怨错误的类型.
知道为什么我这里没有错误吗?
如果我删除use std::io::Read;一切正常.但是,随着范围内的特性突然使用Read的实现,字节具有"错误"类型.
(我正在使用Rust 1.0.0)
@bluss发现了问题:
struct Type;
trait A {
fn foo(&self) -> bool { false }
}
trait B : Sized {
fn foo(self) -> bool { true }
}
impl A for Type { }
impl B for Type { }
fn main() {
println!("{}", Type.foo()); // This will call B::foo -- it will prefer `self`.
}
Run Code Online (Sandbox Code Playgroud)
如果两种类型使用稍微不同的self类型,Rust会将它们视为不同类型,并且调用该方法只是更喜欢其中一种.
这可能是Rust中的一个错误.有关详细信息,请查看相应的Rust问题.