creaple
creaple

Reputation: 155

Why is rust raising error '`()` is not an iterator'?

I tried to write a program that does the following thing: take all suffixes of a given string s, then sort these suffixes with dictionary order.

here is my code:

let mut sorted = (0..s.len())
        .map(|i| (i, &s[i..s.len()]))
        .collect::<Vec<(usize, &str)>>()
        .sort_by_key(|k| k.1);
for elem in sorted {
    println!("{} {}", elem.0, elem.1);
}

and rust compiler gives an error:

error[E0277]: `()` is not an iterator
 --> src/lt05.rs:7:17
  |
7 |     for elem in sorted {
  |                 ^^^^^^ `()` is not an iterator
  |
  = help: the trait `Iterator` is not implemented for `()`
  = note: required for `()` to implement `IntoIterator`

Could anyone please explain what is wrong in this code?

Upvotes: 0

Views: 993

Answers (1)

jq170727
jq170727

Reputation: 14725

Vec::sort_by_key sorts a vector in place and returns (). So in your code sorted ends up being assigned (), the unit type which you can't iterate over.

To fix this you can simply sort the vector after you've constructed it by moving the call to sort_by_key into a separate statement and then iterate over the sorted vector. See example below. Here is a Rust Playground which does this.

fn main() {
    let s = "thisisatest"; 
    
    let mut sorted = 
        (0..s.len())
        .map(|i| (i, &s[i..s.len()]))
        .collect::<Vec<(usize, &str)>>();
        
    sorted.sort_by_key(|k| k.1);
    for elem in sorted {
        println!("{} {}", elem.0, elem.1);
    }
}

Output

6 atest
8 est
1 hisisatest
4 isatest
2 isisatest
5 satest
3 sisatest
9 st
10 t
7 test
0 thisisatest

Upvotes: 2

Related Questions