Skip to content

Using an out-of-scope trait item on a boxed trait object should suggest use-ing the trait #105159

Closed
@shadowfacts

Description

@shadowfacts

Given the following code:

use std::io::{stdin, BufReader};

fn main() {
    let reader: Box<dyn std::io::BufRead> = Box::new(BufReader::new(stdin()));
    let _ = reader.lines();
}

The current output is:

error: the `lines` method cannot be invoked on a trait object
    --> src/main.rs:5:20
     |
5    |     let _ = reader.lines();
     |                    ^^^^^
     |
    ::: /Users/shadowfacts/.rustup/toolchains/nightly-aarch64-apple-darwin/lib/rustlib/src/rust/library/std/src/io/mod.rs:2276:15
     |
2276 |         Self: Sized,
     |               ----- this has a `Sized` requirement

Ideally the output should suggest use-ing the out-of-scope trait, similar to E0599:

error[E0599]: no method named `lines` found for struct `BufReader` in the current scope
    --> src/main.rs:6:20
     |
6    |     let _ = reader.lines();
     |                    ^^^^^ method not found in `BufReader<Stdin>`
     |
    ::: /Users/shadowfacts/.rustup/toolchains/nightly-aarch64-apple-darwin/lib/rustlib/src/rust/library/std/src/io/mod.rs:2274:8
     |
2274 |     fn lines(self) -> Lines<Self>
     |        ----- the method is available for `BufReader<Stdin>` here
     |
     = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
     |
1    | use std::io::BufRead;
     |

Someone tried to do dynamic dispatch between two underlying BufReaders used a boxed trait object (with the type spelled Box<dyn io::BufRead>, so BufRead wasn't in scope) and call the lines method on the boxed reader, and it was unclear from the error why the method wasn't accessible:
https://mastodon.social/@mcc/109441482880682856

This is reproducible on nightly (rustc 1.67.0-nightly (c090c68 2022-12-01)).

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions