Last active
July 28, 2024 13:52
-
-
Save gulbanana/d6f8514f43e0dfe1f66eb0fae5110c83 to your computer and use it in GitHub Desktop.
dyn Trait<T> + 'a
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
trait Provider<T> { | |
fn get(&self) -> T; | |
} | |
struct Owned<T>(T); | |
impl<T: Clone> Provider<T> for Owned<T> { | |
fn get(&self) -> T { | |
self.0.clone() | |
} | |
} | |
struct Borrowed<'a, T>(&'a T); | |
impl<'a, T: Clone> Provider<T> for Borrowed<'a, T> { | |
fn get(&self) -> T { | |
self.0.clone() | |
} | |
} | |
fn select_provider<'a, T: Clone + 'static>(owned: T, borrowed: &'a T) -> Box<dyn Provider<T> + 'a> { | |
let args: Vec<_> = std::env::args().collect(); | |
if let Some("owned") = args.get(1).map(|x| x.as_str()) { | |
Box::new(Owned(owned)) | |
} else { | |
Box::new(Borrowed(borrowed)) | |
} | |
} | |
fn main() { | |
let owned_msg = String::from("Hello, owned world!"); | |
let borrowed_msg = String::from("Hello, borrowed world!"); | |
let provider = select_provider(owned_msg, &borrowed_msg); | |
println!("{}", provider.get()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment