Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Wrapper holding (amoung other things) a vec of entries
- // as well as some values that are constant for all entries
- struct Wrapper {
- entries: Vec<Entry>,
- some_values_constant_for_all_entries: Vec<usize>
- }
- impl Wrapper {
- pub fn new() -> Self {
- let mut entries = Vec::with_capacity(3);
- for val in 0..3 {
- entries.push(Entry { val });
- }
- Wrapper {
- entries,
- some_values_constant_for_all_entries: vec![1,2,4]
- }
- }
- pub fn entries_mut(&mut self) -> &mut Vec<Entry> {
- &mut self.entries
- }
- pub fn constant_values(&self) -> &Vec<usize> {
- &self.some_values_constant_for_all_entries
- }
- }
- // Entry holding a value (and various other things)
- struct Entry {
- val: usize
- }
- impl Entry {
- pub fn update_val(&mut self, update_value: usize, constant_values: &Vec<usize>) {
- //update value based off the update_value and constant_values
- }
- pub fn val(&self) -> usize {
- self.val
- }
- }
- // implementations of the trait define how the values get updated
- trait MyTrait {
- fn calculate_update_value(&self, wrapper: &mut Wrapper);
- }
- struct SomeImpl {
- some_val: usize
- }
- impl MyTrait for SomeImpl {
- fn calculate_update_value(&self, wrapper: &mut Wrapper) {
- for entry in wrapper.entries_mut().iter_mut() {
- let val = entry.val % self.some_val;
- entry.update_val(val, wrapper.constant_values());
- }
- }
- }
- struct Algorithm<T> where T: MyTrait {
- wrapper: Wrapper,
- implementation: T
- }
- impl<T> Algorithm<T> where T: MyTrait {
- fn update(&mut self) {
- self.implementation.calculate_update_value(&mut self.wrapper);
- }
- }
- fn main() {
- let wrapper = Wrapper::new();
- let implementation = SomeImpl { some_val: 5 };
- let mut algorithm = Algorithm {wrapper, implementation};
- algorithm.update();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement