Rust memo1

String Slice

Just a memo of this page

We want to find a first word from a string joined by space.(sentence)

Bad case

1fn first_word(s: &String) -> usize {
2 let bytes = s.as_bytes();
4 for (i, &item) in bytes.iter().enumerate() {
5 if item == b' ' {
6 return i;
7 }
8 }
10 s.len()

This code looks for an index for a first space in the string.

But, this is bad code.

1fn main() {
2 let mut s = String::from("hello world");
4 let word = first_word(&s); // word will get the value 5
6 s.clear(); // this empties the String, making it equal to ""

As shown above, word is still alive even after the string is cleared.

Someone may use the index (word variable) to find a first word.

It no longer exists.

Good case

The article says

Having to worry about the index in word getting out of sync with the data in s is tedious and error prone!.

syncing data is good behavior in Rust.

If you have any questions, please send an email