1

I'm currently working on a data processing project for which I have to store a set of samples with a certain timestamp along with data of different types. There is then a channel struct holding a vector of these samples. I wish to isolate the generic sample from the channel given that I want to hold these channels in a hashmap where I can later retrieve data from a channel by some channel ID.

Given that I wish to isolate the generic sample, I opted for this channel struct to hold a vector of trait objects. Everything seemed to work fine and I managed to fill these channels with my data, but I can't find any way of actually retrieving the data from those samples again.

This is an outline of the code:

trait SampleContainer: Debug {}
impl<T: Debug> SampleContainer for Sample<T> {}

#[derive(Debug)]
struct Sample<T> {
    time: u64,
    data: T
}

#[derive(Debug)]
struct Channel {
    // There would be some channel configuration struct here
    samples: Vec<Box<SampleContainer>>
}

fn main() {
    let new_sample = Box::new(Sample::<u8> {time: 0, data: 10});
    let another_new_sample = Box::new(Sample::<u8> {time: 1, data: 11});

    let mut sample_list: Vec<Box<SampleContainer>> = Vec::new();
    sample_list.push(new_sample);
    sample_list.push(another_new_sample);

    let mut channel_list: HashMap<u16, Channel> = HashMap::new();
    let new_channel = Channel {samples: sample_list};

    channel_list.insert(1, new_channel);

    // This prints what I would expect: [Sample { time: 0, data: 10 }, Sample { time: 1, data: 11 }]
    println!("{:?}", channel_list[&1].samples);
}

How would I access the underlying sample data in my channels? Or am I going about this wrong entirely?

I look forward to receiving any input!

jonny
  • 3,022
  • 1
  • 17
  • 30
R Vorster
  • 11
  • 3
  • 1
    This might be an XY problem, but it's hard to tell without more info. You might rather want a enum with each type, or a set of methods in the trait that describe what you can do with it. – JayDepp Mar 07 '19 at 02:22
  • I would suggest, if at all possible, simplifying your data representation. Is there a reason why you're using trait objects specifically? Or could it be better solved with a simple enum? [Here's a playground link with an alternative implementation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=01909cd5c2579cbba7484cdb21f685fa) – jonny Mar 07 '19 at 17:14
  • Thank you @jonny, I did indeed go with an enum. It seemed like a more cumbersome solution at first, but now that I've implemented it it greatly simplifies the code. – R Vorster Mar 08 '19 at 09:24
  • @apemanzilla, this does work for me, although in the end I went with an entirely different approach. I will mark the question as a duplicate. Thank you! – R Vorster Mar 08 '19 at 09:25

0 Answers0