【问题标题】:No error for two traits implementing the same method实现相同方法的两个特征没有错误
【发布时间】:2015-06-07 21:21:27
【问题描述】:

根据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 会抱怨与上述相同的错误。相反,它默默地选择了“错误”的实现,后来println 抱怨错误的类型。

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

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

(我使用的是 Rust 1.0.0)

【问题讨论】:

标签: rust mio


【解决方案1】:

@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

【讨论】:

  • 我只是被它这样的工作方式难住了,现在我认为我们不能称之为错误。 Rust 是稳定的,所以我们需要对这个特性友好。 :-|
猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 2022-11-02
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多