From: Martin Pitt Date: Sun, 22 Aug 2021 13:21:27 +0000 (+0200) Subject: References, slices, Option X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=a622f4b9138f7e21ddf616d325a0a2cddbc227ff References, slices, Option --- a622f4b9138f7e21ddf616d325a0a2cddbc227ff 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), + } +}