Last active
August 13, 2023 08:43
-
-
Save brahmlower/e0195fde7f6e31e65814320279ab7340 to your computer and use it in GitHub Desktop.
A quick demo of using DynClone on a trait so structs with `dyn TraitName` can derive Clone
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
#!/usr/bin/env cargo +nightly -Zscript | |
//! ```cargo | |
//! [dependencies] | |
//! dyn-clone = "1.0.12" | |
//! ``` | |
use std::fmt::Debug; | |
use dyn_clone::DynClone; | |
trait AProvider: DynClone + Debug { | |
fn provider_name(&self) -> &str; | |
} | |
dyn_clone::clone_trait_object!(AProvider); | |
#[derive(Clone, Debug)] | |
struct AXProvider {} | |
impl AProvider for AXProvider { | |
fn provider_name(&self) -> &str { | |
"AXProvider" | |
} | |
} | |
#[derive(Clone, Debug)] | |
struct AYProvider {} | |
impl AProvider for AYProvider { | |
fn provider_name(&self) -> &str { | |
"AYProvider" | |
} | |
} | |
#[derive(Clone, Debug)] | |
struct AController { | |
providers: Vec<Box<dyn AProvider>>, | |
} | |
impl AController { | |
pub fn print_providers(&self) { | |
for p in &self.providers { | |
println!("{}", p.provider_name()); | |
} | |
} | |
} | |
trait HasAController { | |
fn a_controller(&self) -> &AController; | |
} | |
#[derive(Clone, Debug)] | |
struct AppState { | |
a_controller: AController, | |
} | |
impl HasAController for AppState { | |
fn a_controller(&self) -> &AController { | |
&self.a_controller | |
} | |
} | |
fn main() { | |
let x = AXProvider{}; | |
let y = AYProvider{}; | |
let ac = AController { | |
providers: vec![ | |
Box::new(x), | |
Box::new(y) | |
], | |
}; | |
let state = AppState { | |
a_controller: ac, | |
}; | |
needs_acontroller(&state) | |
} | |
fn needs_acontroller<S: HasAController>(state: &S) { | |
state.a_controller().print_providers(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment