Почему перебор строки не выполняет код после цикла? - PullRequest
0 голосов
/ 07 ноября 2019

Я читаю о типе среза . Я запутался в части примера в функции first_word.

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s); // word will get the value 5

    s.clear(); // this empties the String, making it equal to ""

    // word still has the value 5 here, but there's no more string that
    // we could meaningfully use the value 5 with. word is now totally invalid!
    println!("|{}| - {}", s, word)
}

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();
    println!("head {}", s.len());
    for (i, &item) in bytes.iter().enumerate() {
        println!("index: {} - item: {} - length: {}", i, item, s.len());
        if item == b' ' {
            return i;
        }
    }
    println!("tail {}", s.len());
    s.len()
}

Результат:

head 11
index: 0 - item: 104 - length: 11
index: 1 - item: 101 - length: 11
index: 2 - item: 108 - length: 11
index: 3 - item: 108 - length: 11
index: 4 - item: 111 - length: 11
index: 5 - item: 32 - length: 11
|| - 5
  1. Что случилось с s.len(), почемувернуть 5 вместо всей строки "hello world", как часть цикла?
  2. Где результат:

    println!("tail {}", s.len());
    
...