Created
March 20, 2020 01:12
-
-
Save NebulaFox/4b9f3823a728a69f07ce784ede3299f9 to your computer and use it in GitHub Desktop.
Wrap type implementing AsRef<str>
This file contains 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; | |
#[derive(Debug, PartialEq)] | |
struct Wrap<T> { | |
inside: T | |
} | |
impl<T> Wrap<T> { | |
fn new(inside: T) -> Wrap<T> { | |
Wrap { | |
inside | |
} | |
} | |
} | |
impl<T> AsRef<str> for Wrap<T> | |
where | |
T: AsRef<str>, | |
{ | |
fn as_ref(&self) -> &str { | |
self.inside.as_ref() | |
} | |
} | |
fn make_a_string_with_ref<S>(string: S) -> String | |
where | |
S: AsRef<str>, | |
{ | |
let mut s = String::new(); | |
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 slice = "Hello World"; | |
let string = String::from(slice); | |
let wrap_literal = Wrap::new("panic"); | |
let wrap_slice = Wrap::new(slice); | |
let wrap_string = Wrap::new(String::from(slice)); | |
let wrap_ref_string = Wrap::new(&string); | |
// wraps are moved | |
let array: &[String] = &[ | |
make_a_string_with_ref(wrap_literal), | |
make_a_string_with_ref(wrap_slice), | |
make_a_string_with_ref(wrap_string), | |
make_a_string_with_ref(wrap_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