mirror of https://github.com/KaiserY/trpl-zh-cn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
25 lines
572 B
25 lines
572 B
3 years ago
|
fn first_word(s: &String) -> usize {
|
||
|
let bytes = s.as_bytes();
|
||
|
|
||
|
for (i, &item) in bytes.iter().enumerate() {
|
||
|
if item == b' ' {
|
||
|
return i;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
s.len()
|
||
|
}
|
||
|
|
||
|
// ANCHOR: here
|
||
|
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!
|
||
|
}
|
||
|
// ANCHOR_END: here
|