Recommendations about references to other field of the same struct

⚓ rust    📅 2025-05-31    👤 surdeus    👁️ 3      

surdeus

I've these types that compile (I'm surprised that using the references in the same struct compiles), but I can't use them later.

Here it's the whole example:

use futures::{stream, StreamExt};
use std::{
    collections::{BTreeMap, HashMap},
    vec::IntoIter,
};

trait Processable {
    fn code(&self) -> String;
    fn priority(&self) -> u32;
}

struct Operation {
    queue: stream::Iter<IntoIter<Item>>,
}

struct Item {
    code: String,
    priority: u8,
}

struct Processor<'a, T: Processable> {
    processables: HashMap<String, T>,
    priority: BTreeMap<u32, Vec<&'a T>>,
}

So, my question is, what's the best approach?

  • Pin: I don't fully understand it, so I'd rather avoid it unless someone explain it to me.
  • Rc: It's !Send, so I couldn't use it because I'm using async code. Apart from that, allocating hundreds or thousands of Rc + Weak doesn't looks good.
  • Arc: I don't need Sync, Mutex, etc.
  • Indexes: Storing the indexes or the codes in the BTreeMap is simple but it means looking up in the HashMap for everything, instead of just accessing the T through a reference.

What would you do?

3 posts - 3 participants

Read full topic

🏷️ rust_feed