trpl-zh-cn/listings/ch04-understanding-ownership/listing-04-09/src/main.rs
tanliwei af1768d9f2
fix a typo
fix a typo
2022-02-09 14:56:11 +08:00

37 lines
1022 B
Rust
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// ANCHOR: here
fn first_word(s: &str) -> &str {
// ANCHOR_END: here
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
// ANCHOR: usage
fn main() {
let my_string = String::from("hello world");
// `first_word` 适用于 `String`(的 slice整体或全部
let word = first_word(&my_string[0..6]);
let word = first_word(&my_string[..]);
// `first_word` 也适用于 `String` 的引用,
// 这等价于整个 `String` 的 slice
let word = first_word(&my_string);
let my_string_literal = "hello world";
// `first_word` 适用于字符串字面值,整体或全部
let word = first_word(&my_string_literal[0..6]);
let word = first_word(&my_string_literal[..]);
// 因为字符串字面值已经 **是** 字符串 slice 了,
// 这也是适用的,无需 slice 语法!
let word = first_word(my_string_literal);
}
// ANCHOR_END: usage