Hello, I am trying to access data elements guarded by an Arc<Mutex<Vec>>. The get function below is a causing the following compile error: 'cannot return value referencing local variable.' This makes sense however I am struggling to come up with the right solution. Any insights are appreciated..
use std::sync::{Arc, Mutex};
struct Data {
guarded_data: Arc<Mutex<Vec>>,
}
impl Data {
pub fn new() -> Data {
let v: Vec = vec!;
Data {
guarded_data: Arc::new(Mutex::new(v)),
}
}
fn add(&self, n: i32) {
let mut d = self.guarded_data.lock().unwrap();
d.push(n)
}
fn get(&self, index: usize) -> &i32 {
let d = self.guarded_data.lock().unwrap();
d.get(index).unwrap()
}
}
fn main() {
let data = Data::new();
data.add(1);
let n = data.get(0);
println!("Result: {}", n);
}
You can't keep a reference to the locked "thing" without holding the lock.
The simplest solution, in the case of i32 or similar types, is to return a copy (i32 instead of &i32) or clone. In other cases, where you don't want to clone the value, you can design the API so that it takes a closure operating on the locked &i32.
@new2rust If you can work with immutable values, then using a Mutex<Arc<Value>> will be a quick solution. Just clone the Arc and return the clone.
If that turns out to be too slow, or otherwise not practable, you will need to provide a lot more information as there are lots of possible solutions, all with different tradeoffs…