Swap function errors with lifetime mismatch

I have a snippet of code that swaps two variables memory, which works fine:

let mut last_input = InputState::default();
let mut current_input = InputState::default();
let temp = current_input;
current_input = last_input;
last_input = temp;

However, when I extract the swap logic into a function I get the following errors:

lifetime mismatch... but data from `last_input` flows into `current_input` hererustc E0623 main.rs(168, 57): these two types are declared with different lifetimes... main.rs(168, 28):

I can't figure out how to annotate the lifetimes to tell the borrow checker that this is okay. Any suggestions?

It would be useful to see the types and function signatures involved. From the error, it sounds like you might be able to fix it by using the same named lifetime for both arguments, e.g.:

fn swap<'a>(a: &mut InputState<'a>, b: &mut InputState<'a>)

But you might also be able to just use the std::mem::swap function.

1 Like

Thanks, std::mem::swap was exactly what I needed.