Last active
May 9, 2020 18:30
-
-
Save aboglioli/69d31a5c0009bc22c579bceb06a44710 to your computer and use it in GitHub Desktop.
Trait object passed as generic argument by using ?Sized as relaxation.
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 std::fmt; | |
trait Handler: fmt::Debug { | |
fn handle(&mut self); | |
} | |
#[derive(Debug)] | |
struct Value(i32); | |
#[derive(Debug)] | |
struct Data { | |
value: Value, | |
} | |
impl Default for Data { | |
fn default() -> Self { | |
Data { value: Value(0) } | |
} | |
} | |
impl Handler for Data { | |
fn handle(&mut self) { | |
self.value.0 += 1; | |
println!("- value: {:?}", self); | |
} | |
} | |
fn proc<H: Handler + ?Sized>(h: &mut H) { | |
h.handle(); | |
} | |
// Equivalent | |
// fn proc(h: &mut dyn Handler) { | |
// h.handle(); | |
// } | |
fn main() { | |
let mut d: Box<dyn Handler> = Box::new(Data::default()); | |
d.handle(); | |
proc(d.as_mut()); | |
println!("{:?}", d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment