Created
March 20, 2020 01:01
-
-
Save NebulaFox/6c950c1b8563cb23d9fe5623c4253c2c to your computer and use it in GitHub Desktop.
Wrap type implementing Into<String>
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> Into<String> for Wrap<T> | |
where | |
T: Into<String>, | |
{ | |
fn into(self) -> String { | |
self.inside.into() | |
} | |
} | |
fn make_a_string_with_into<S>(string: S) -> String | |
where | |
S: Into<String>, | |
{ | |
let mut s = string.into(); | |
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_into(wrap_literal), | |
make_a_string_with_into(wrap_slice), | |
make_a_string_with_into(wrap_string), | |
make_a_string_with_into(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