summaryrefslogtreecommitdiffstats
path: root/src/doc/book/listings/ch04-understanding-ownership/listing-04-08
diff options
context:
space:
mode:
Diffstat (limited to 'src/doc/book/listings/ch04-understanding-ownership/listing-04-08')
-rw-r--r--src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock6
-rw-r--r--src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml6
-rw-r--r--src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs24
3 files changed, 36 insertions, 0 deletions
diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock
new file mode 100644
index 000000000..2aa4918e5
--- /dev/null
+++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.lock
@@ -0,0 +1,6 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "ownership"
+version = "0.1.0"
+
diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml
new file mode 100644
index 000000000..e8847526d
--- /dev/null
+++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "ownership"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
diff --git a/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs
new file mode 100644
index 000000000..b6182fe2b
--- /dev/null
+++ b/src/doc/book/listings/ch04-understanding-ownership/listing-04-08/src/main.rs
@@ -0,0 +1,24 @@
+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