Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Last active May 9, 2020 18:30
Show Gist options
  • Save aboglioli/69d31a5c0009bc22c579bceb06a44710 to your computer and use it in GitHub Desktop.
Save aboglioli/69d31a5c0009bc22c579bceb06a44710 to your computer and use it in GitHub Desktop.
Trait object passed as generic argument by using ?Sized as relaxation.
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