From a622f4b9138f7e21ddf616d325a0a2cddbc227ff Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sun, 22 Aug 2021 15:21:27 +0200 Subject: [PATCH] References, slices, Option --- Cargo.toml | 8 ++++++++ src/main.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 Cargo.toml create mode 100644 src/main.rs diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a642e49 --- /dev/null +++ b/Cargo.toml @@ -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 index 0000000..83d94c6 --- /dev/null +++ b/src/main.rs @@ -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), + } +} -- 2.39.5