I am not sure if I had came up with an accurate title.
I want to continuously receive user input and get its reference, then proceed to request the next user input. However, I am looking for a way to ensure that all user input values have a fixed lifetime, lasting until the end of the function.
This issue arises when using the wgpu library. The RenderPass class's member functions require that the lifetime of the references in the arguments should be at least as long as the RenderPass's lifetime parameter. (e.g. set_pipeline
)
// imagine: this struct was provided by an external library.
struct Limiter<'a> {
internal: &'a i32,
}
impl<'a> Limiter<'a> {
fn new(internal: &'a i32) -> Self {
Limiter { internal }
}
fn set(&mut self, reference: &'a i32) {
self.internal = reference;
}
}
// imagine: this function would get a value from console
fn get_value_from_console() -> i32 {
0
}
fn main() {
let initial = 0;
let mut limiter = Limiter::new(&initial);
/*
// Attemp #1: failed. borrowed value does not live long enough
let mut value_keeper: Vec<i32> = Vec::new();
for _ in 0..100 {
let mut value = get_value_from_console();
limiter.set(&mut value);
}
*/
/*
// Attemp #2: failed. cannot borrow `value_keeper` as mutable because it is also borrowed as immutable
let mut value_keeper: Vec<i32> = Vec::new();
for _ in 0..100 {
value_keeper.push(get_value_from_console());
limiter.set(value_keeper.last().unwrap());
}
*/
// Attemp #3: succeeded. But I have to wait for all inputs before invoking `limiter.set`
let zeros = (0..100).map(|_| get_value_from_console()).collect::<Vec<_>>();
for i in 0..100 {
limiter.set(&zeros[i]);
}
}