Skip to content

Error refers to the wrong span of code #90321

Closed
@cubetastic33

Description

@cubetastic33

Given the following code:

use rand::prelude::*;
use std::collections::HashSet;

fn main() {
    let mut foo = vec![String::new(); 10];
    let bar: HashSet<_> = "bar".chars().collect();
    let mut fubar: HashSet<_> = "fubar".chars().collect();
    let baz = vec![(String::new(), bar)];
    let mut rng = thread_rng();
    
    let choice = baz.choose(&mut rng).unwrap();
    foo.push(choice.0.clone());
    
    fubar = fubar.difference(&choice.1).collect();
    
    // Uncomment to get the correct error in nightly
    // foo = vec![String::new(); 10];
    foo.shuffle(&mut rng);
}

The error reported by rust nightly/beta is:

error[E0277]: a value of type `HashSet<char>` cannot be built from an iterator over elements of type `&char`
  --> src/main.rs:18:17
   |
18 |     foo.shuffle(&mut rng);
   |         ------- ^^^^^^^^ value of type `HashSet<char>` cannot be built from `std::iter::Iterator<Item=&char>`
   |         |
   |         required by a bound introduced by this call
   |
   = help: the trait `FromIterator<&char>` is not implemented for `HashSet<char>`

For more information about this error, try `rustc --explain E0277`.

Playground

But the error clearly doesn't belong there - it's supposed to be on line 14. Rust stable shows the correct error, and re-assigning to foo just before the shuffle makes the correct error show on nightly and beta as well.

This is what the error should be:

error[E0277]: a value of type `HashSet<char>` cannot be built from an iterator over elements of type `&char`
  --> src/main.rs:14:41
   |
14 |     fubar = fubar.difference(&choice.1).collect();
   |                                         ^^^^^^^ value of type `HashSet<char>` cannot be built from `std::iter::Iterator<Item=&char>`
   |
   = help: the trait `FromIterator<&char>` is not implemented for `HashSet<char>`

For more information about this error, try `rustc --explain E0277`.

Metadata

Metadata

Assignees

No one assigned

    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