Last active
May 9, 2020 06:11
-
-
Save aboglioli/d8ab2fa8fc7e8e9ac6e8227f872a4952 to your computer and use it in GitHub Desktop.
Iterator<Item = &'a mut T> on trait objects.
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; | |
use std::slice::IterMut; | |
/** | |
* Data | |
*/ | |
trait Data: fmt::Debug { | |
fn add_value(&mut self, v: i32); | |
} | |
#[derive(Debug)] | |
struct ImplData { | |
value: i32, | |
} | |
impl Data for ImplData { | |
fn add_value(&mut self, v: i32) { | |
self.value += v; | |
} | |
} | |
impl Default for ImplData { | |
fn default() -> Self { | |
ImplData { value: 0 } | |
} | |
} | |
/** | |
* Processor | |
*/ | |
// Cannot be made into trait object | |
trait StaticProcessor { | |
fn process<'a, I>(&self, iter: I) | |
where | |
I: Iterator<Item = &'a mut Box<dyn Data>>; | |
} | |
// Dynamic dispatch, trait object | |
trait DynProcessor { | |
fn process<'a>(&self, iter: Box<dyn Iterator<Item = &mut Box<dyn Data>> + 'a>); | |
} | |
// As mutable reference | |
// trait DynProcessor { | |
// fn process(&self, iter: &mut dyn Iterator<Item = &mut Box<dyn Data>>); | |
// } | |
struct Processor1; | |
impl DynProcessor for Processor1 { | |
fn process<'a>(&self, iter: Box<dyn Iterator<Item = &mut Box<dyn Data>> + 'a>) | |
{ | |
for (i, data) in iter.enumerate() { | |
data.add_value(i as i32); | |
} | |
} | |
} | |
struct Processor2; | |
impl DynProcessor for Processor2 { | |
fn process<'a>(&self, iter: Box<dyn Iterator<Item = &mut Box<dyn Data>> + 'a>) | |
{ | |
for (i, data) in iter.enumerate() { | |
data.add_value(2 * i as i32); | |
} | |
} | |
} | |
fn main() { | |
let d1 = ImplData::default(); | |
let d2 = ImplData::default(); | |
let d3 = ImplData::default(); | |
let mut v: Vec<Box<dyn Data>> = vec![Box::new(d1), Box::new(d2), Box::new(d3)]; | |
let processor1 = Processor1; | |
let processor2 = Processor2; | |
// processor1.process(Box::new(v.iter_mut())); | |
// processor2.process(Box::new(v.iter_mut())); | |
let processors: Vec<Box<dyn DynProcessor>> = vec![Box::new(processor1), Box::new(processor2)]; | |
for processor in processors.iter() { | |
processor.process(Box::new(v.iter_mut())); | |
} | |
println!("{:?}", v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment