实现相同方法的两个特征没有错误

No error for two traits implementing the same method

根据 the docs,如果我尝试调用由两个不同特征提供的方法,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();
}

运行 这会导致预期的 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);
}

mio::buf::RingBuf 同时实现了 BufRead。这两个特征都提供了一个 bytes 方法。

我希望 Rust 会抱怨与上述相同的错误。相反,它默默地选择 "wrong" 实现,后来 println 抱怨错误的类型。

知道为什么我在这里没有收到错误消息吗?

如果我删除 use std::io::Read; 一切正常。但是由于范围内的这种特性突然使用了 Read 的实现并且 bytes 具有 "wrong" 类型。

(我使用的是 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`.
}

如果两种类型使用略有不同的 self 类型,Rust 将它们视为不同的并且调用方法只是更喜欢其中之一。

这可能是 Rust 中的一个错误。详情请看对应的Rust issue.