Rust Lifetime Conundrum

I’m not really one that asks for help, but just this once I’m going to see if it can solve my problem faster than I would eventually.
So, I have this:

pub struct BFBlock<'a> {
	pub instructions: Vec<&'a mut dyn Instruction>
}

impl<'a> BFBlock<'a> {
	pub fn new() -> BFBlock<'a> {
		return BFBlock {
			instructions: Vec::new()
		};
	}
	
	pub fn add(&mut self, mut instruction: Box<dyn Instruction>) {
        // argument requires that `*instruction` is borrowed for `'a`
		self.instructions.push(&mut *instruction);
	}
}

And in another function I have things like this:

let mut sum = Add::new(left, right);

branch.add(Box::new(sum));

I can’t make the argument for add a reference because the struct constructed in the function doesn’t live as long as branch
I need some way to move it in a way add can take ownership and insert it into the vector.
I started using Box since I can move the struct into the box and pass the box, but I haven’t been able to get that to work either.
Normally I would simply pass a non reference so that the argument ownership gets transferred, but since Instruction is a trait I can’t do that.

Hello there, @CSharpIsGud. You might get better help if you change it to #code-help and then set the tag to what you are using. Like I would use #code-help:python for python.

It is in #code-help and there isn’t a tag for rust.

1 Like

Ok, sorry about that. You’ll just have to probably wait for someone way smarter them me for them to help. Enjoy your time!

Okay I had a stroke of genius and BOOM

pub fn add<T>(&mut self, instruction: T) where T: Instruction + 'a {
	self.instructions.push(Box::new(instruction));
}

Generics are awesome

3 Likes

Is this the solution? If so, you should mark it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.