Search code examples
rustiteratorenumerate

How do I enumerate on a vector of Strings?


let output_sorted: Vec<String> = four_digit_ouput
        .iter()
        .map(|tok| tok.chars().sorted().collect::<String>())
        .collect();

let output = 0;
for (idx, digit) in output_sorted.enumerate() {

I get this error when I try to do an enumerating for loop over a vector of strings:

error[E0599]: the method `enumerate` exists for struct `Vec<String>`, but its trait bounds were not satisfied
   --> src\day8.rs:185:39
    |
185 |     for (idx, digit) in output_sorted.enumerate() {}
    |                                       ^^^^^^^^^ method cannot be called on `Vec<String>` due to unsatisfied trait bounds
    |
   ::: C:\Users\b\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\alloc\src\vec\mod.rs:400:1
    |
400 | pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
    | ------------------------------------------------------------------------------------------------ doesn't satisfy `Vec<String>: Iterator`
    |
    = note: the following trait bounds were not satisfied:
            `Vec<String>: Iterator`
            which is required by `&mut Vec<String>: Iterator`
            `[String]: Iterator`
            which is required by `&mut [String]: Iterator`
    
For more information about this error, try `rustc --explain E0599`.

What's going on? What trait bounds do not allow this to enumerate?


Solution

  • A vector is not an Iterator.

    Use output_sorted.iter().enumerate() (to consult), output_sorted.iter_mut().enumerate() (to modify) oroutput_sorted.into_iter().enumerate() (to consume).

    Note that when using a for loop directly on a vector, an implicit call to into_iter() is made; this could be interpreted as if the vector was itself an Iterator but it is just a convenience from the language.