]> git.proxmox.com Git - rustc.git/blobdiff - src/doc/book/listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch10-generic-types-traits-and-lifetimes / listing-10-25 / src / main.rs
index 2937b194cab7f2a1a66549d818b620ff3b71f8a7..431a261d2c7bf497b094ec2498b5703b9a4500f0 100644 (file)
@@ -1,11 +1,29 @@
-struct ImportantExcerpt<'a> {
-    part: &'a str,
+// ANCHOR: here
+fn first_word(s: &str) -> &str {
+    let bytes = s.as_bytes();
+
+    for (i, &item) in bytes.iter().enumerate() {
+        if item == b' ' {
+            return &s[0..i];
+        }
+    }
+
+    &s[..]
 }
+// ANCHOR_END: here
 
 fn main() {
-    let novel = String::from("Call me Ishmael. Some years ago...");
-    let first_sentence = novel.split('.').next().expect("Could not find a '.'");
-    let i = ImportantExcerpt {
-        part: first_sentence,
-    };
+    let my_string = String::from("hello world");
+
+    // first_word works on slices of `String`s
+    let word = first_word(&my_string[..]);
+
+    let my_string_literal = "hello world";
+
+    // first_word works on slices of string literals
+    let word = first_word(&my_string_literal[..]);
+
+    // Because string literals *are* string slices already,
+    // this works too, without the slice syntax!
+    let word = first_word(my_string_literal);
 }