Skip to content

Consider suggesting &mut TypeParam when given &TypeParam and that would fix the user's issue #81421

Closed
@estebank

Description

@estebank

When given:

fn communicate_with_server<T: Read + Write>(mut stream: T) {
    let initial_message = format!("hello world");
    let mut buffer: Vec<u8> = Vec::new();
    let _bytes_written = stream.write_all(initial_message.as_bytes());
    let _flush = stream.flush();

    loop {
        let mut stream_reader = BufReader::new(&stream);
        stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed");
    }
}

We currently emit:

error[E0277]: the trait bound `&T: std::io::Read` is not satisfied
  --> src/main.rs:13:48
   |
13 |         let mut stream_reader = BufReader::new(&stream);
   |                                                -^^^^^^
   |                                                |
   |                                                the trait `std::io::Read` is not implemented for `&T`
   |                                                help: consider removing the leading `&`-reference
   |
   = note: required by `BufReader::<R>::new`

error[E0599]: no method named `read_until` found for struct `BufReader<&T>` in the current scope
  --> src/main.rs:14:23
   |
14 |           stream_reader.read_until(b'\n', &mut buffer).expect("Reading into buffer failed");
   |                         ^^^^^^^^^^ method not found in `BufReader<&T>`
   |
   = note: the method `read_until` exists but the following trait bounds were not satisfied:
           `&T: std::io::Read`
           which is required by `BufReader<&T>: BufRead`

What is likely desired instead is to use &mut Stream.

Seen in the wild at https://www.reddit.com/r/rust/comments/l5osgu/why_does_a_reference_to_a_generic_parameter_not/

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`A-type-systemArea: Type systemD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-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