Trait with lifetime with method returning the same struct with different lifetime

⚓ Rust    📅 2025-10-20    👤 surdeus    👁️ 2      

surdeus

I want to define a trait which allows interning combined with bumpalo allocator.

struct Bump;

trait View<'a> {
    fn intern_key(&self) -> &'a str;

    // ERROR!
    fn intern<'arena>(&self, arena: &'arena Bump) -> (&'arena str, Self<'arena>);
}

struct Interner<'arena, T> {
  items: HashMap<&'arena str, T>,
  arena: &'arena Bump,
}

impl<'arena, T: View<'arena> + Copy> {
  fn add<'a>(&mut self, obj: View<'a>) {
    let (key, interned) = obj.intern();
    self.items.insert(key, interned);
  }

  fn get(&self, key: &str) -> Option<T> {
    self.items.get(key).copied()
  }
}

FYI i'm using Bump as I don't want to give Interner lifetime bounded T in get method.

The problem is, this code won't compile as trait cannot say Self<'a>, it must be Self.

1 post - 1 participant

Read full topic

🏷️ Rust_feed