Testing exercises/standard_library_types/iterators2.rs

rustlings, I modified iterators2.rs as follows, I cannot build this test.
the build spends a lot of time with no result.
Please help me.

pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
let mut result = String::new();
while let Some(first) = c.next() {
    let len = result.len();
    if len == 0 {
        result.push(first.to_ascii_uppercase());
    } else {
        result.push(first);
    }
}
result

}

#[cfg(test)]
mod tests {
use super::*;

// Step 1.
// Tests that verify your `capitalize_first` function implementation
#[test]
fn test_success() {
    assert_eq!(capitalize_first("hello"), "Hello");
}

#[test]
fn test_empty() {
    assert_eq!(capitalize_first(""), "");
}

// Step 2.
#[test]
fn test_iterate_string_vec() {
    let words = vec!["hello", "world"];
    let capitalized_words: Vec<_> = words.iter().map(|&word| capitalize_first(word)).collect(); // TODO
    assert_eq!(capitalized_words, ["Hello", "World"]);
}

#[test]
fn test_iterate_into_string() {
    let words = vec!["hello", " ", "world"];
    let mut capitalized_words: String = String::new();
    while let Some(&word) = words.iter().next() {
        let str = capitalize_first(word);
        capitalized_words.push_str(&str);
    }
    assert_eq!(capitalized_words, "Hello World");
}

}Preformatted text

In the future try to format the code completely so it shows up nicely in the forum. The easiest way is to put all the code between a pair of three backticks like so

```
Put your code here
```

As far as your question, your last test has the following line

while let Some(&word) = words.iter().next() {

This is creating a new iterator that starts from the beginning of the vector for each time through the loop, making an infinite loop. This can either be changed to

let mut iter = words.iter();
while let Some(&word) = iter.next() {

Or you can just use a for loop directly which wouldn’t have this problem to worry about

for word in words.iter() {

The for loop syntax effectively handles the reuse of the same iterator for you

Thanks for your help

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.