Created
March 20, 2020 02:59
-
-
Save NebulaFox/5456bb20fadeb06ec7cb893b3b55fa18 to your computer and use it in GitHub Desktop.
strings wrapped up in Option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rand; // 0.7.3 | |
use rand::Rng; | |
fn make_a_string_with_optional<S>(option: Option<S>) -> String | |
where | |
S: AsRef<str>, | |
{ | |
let mut s = String::from("Hello"); | |
if let Some(string) = option { | |
s.push_str(" "); | |
s.push_str(string.as_ref()); | |
} | |
let mut rng = rand::thread_rng(); | |
let r = rng.gen_range(0, 100); | |
for _ in 0..r { | |
s.push_str("!"); | |
} | |
s | |
} | |
fn main() { | |
let world_slice = "World"; | |
let world_string = String::from(world_slice); | |
let none = make_a_string_with_optional(None::<&str>); | |
let some_literal = make_a_string_with_optional(Some("Ferris")); | |
let some_slice = make_a_string_with_optional(Some(world_slice)); | |
let some_string = make_a_string_with_optional(Some(String::from(world_slice))); | |
let some_ref_string = make_a_string_with_optional(Some(&world_string)); | |
let array: &[String] = &[none, some_literal, some_slice, some_string, some_ref_string]; | |
for s in array.iter() { | |
println!("len: {}, string: {}", s.len(), s) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment