]> piware.de Git - learn-rust.git/commitdiff
References, slices, Option
authorMartin Pitt <martin@piware.de>
Sun, 22 Aug 2021 13:21:27 +0000 (15:21 +0200)
committerMartin Pitt <martin@piware.de>
Sun, 22 Aug 2021 13:21:27 +0000 (15:21 +0200)
Cargo.toml [new file with mode: 0644]
src/main.rs [new file with mode: 0644]

diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644 (file)
index 0000000..a642e49
--- /dev/null
@@ -0,0 +1,8 @@
+[package]
+name = "learning"
+version = "0.1.0"
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
diff --git a/src/main.rs b/src/main.rs
new file mode 100644 (file)
index 0000000..83d94c6
--- /dev/null
@@ -0,0 +1,33 @@
+fn first_word(s: &str) -> &str {
+    for (i, &item) in s.as_bytes().iter().enumerate() {
+        if item == b' ' {
+            return &s[..i];
+        }
+    }
+
+    s
+}
+
+fn second_word(s: &str) -> Option<&str> {
+    for (i, &item) in s.as_bytes().iter().enumerate() {
+        if item == b' ' {
+            return Some(first_word(&s[(i + 1)..]));
+        }
+    }
+
+    return None;
+}
+
+fn main() {
+    let s = String::from("Hello world");
+    println!("first word: '{}'", first_word(&s));
+    println!("second word: '{}'", second_word(&s).unwrap());
+
+    let s2 = "hello dude blah";
+    println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
+
+    match second_word(s2) {
+        Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
+        None => println!("match: second word of '{}' does not exist", s2),
+    }
+}