Trait object use and array & slice

Hello,
I have following trait implemented for u32, I am struggling with writing function signature for additional_processing so that I can do some processing on a slice of the last half of the array. Can someone guide me? Thank you.

trait Pulse {
  fn empty() -> Self;
  fn do_something(&self) -> bool;
}
impl Pulse for u32 {
  fn empty() -> Self { 0 }
  fn do_something(&mut self) -> bool {
    ....
  }
}

fn main() {
  let mut data: [u32; 32] = [Pulse::empty(); 32];

  // do something on `data` in this main
  for e in &data[..data.len()] {
    if entry.do_something() { .. } esle { .. }
  }

  // then want to process a slice of `data` via a function e.g. on last 16 elements
  additional_processing( ??? );
}

fn additional_processing( ??? ) {

}

do you want a generic function that can accept any type implementing the trait Pulse? if so, the signature should look like:

fn additional_processing<T: Pulse>(data: &mut [T]);

EDIT:

noticed the trait method use &mut self, so changed to a mut slice, and call it like this:

  let mut data: [u32; 32] = [Pulse::empty(); 32];
  additional_processing(&mut data[data.len()/2 ..]);
3 Likes

Something like this, maybe:

trait Pulse {
    fn empty() -> Self;
    fn do_something(&mut self) -> bool;
}

impl Pulse for u32 {
    fn empty() -> Self {
        0
    }
    fn do_something(&mut self) -> bool {
        eprintln!("do_something: {self}");
        true
    }
}

fn main() {
    let mut data: [u32; 32] = [Pulse::empty(); 32];

    // do something on `data` in this main
    for entry in &mut data[..] {
        if entry.do_something() {
            dbg!(true);
        } else {
            dbg!(false);
        }
    }

    // then want to process a slice of `data` via a function e.g. on last 16 elements
    let n = data.len();
    additional_processing(&mut data[(n / 2)..]);
}

fn additional_processing<T: Pulse>(arr: &mut [T]) {
    for x in arr {
        x.do_something();
    }
}
1 Like

Thank you, that works!

Thank you, it works!