Hi All,
I am trying to make the following code work:
use ghostcell::GhostToken;
use ghostcell::GhostCell;
use std::vec::Vec;
pub fn counter<'id>(
token : &mut GhostToken<'id>,
n : i64
) -> Vec<&GhostCell<'id, i64>> {
let c = GhostCell:: new (n);
let vec: Vec<_> = (0..1).map(|_|&c).collect();
vec
}
fn main() {
GhostToken::new(|mut token| {
let vec = counter(&mut token, 0);
let a: &i64 = vec[0].borrow_mut(&mut token);
*a = *a + 1;
println!("{}", a);
let b: &i64 = vec[1].borrow_mut(&mut token);
*b = *b + 1;
println!("{}", b);
});
}
Based on my understanding, shared ghost cells need to be put into a container and uses the token to access it. But a function returning a vector needs lifetime parameters. See the error below:
token : &mut GhostToken<'id>,
| --------------------
7 | n : i64
8 | ) -> Vec<&GhostCell<'id, i64>> {
| ^ expected named lifetime parameter
Adding a lifetime parameter:
pub fn counter<'a, 'id>(
token : &mut GhostToken<'id>,
n : i64
) -> Vec<& 'a GhostCell<'id, i64>> {
let c = GhostCell:: new (n);
let vec: Vec<_> = (0..1).map(|_|&c).collect();
vec
}
It will complain:
let vec: Vec<_> = (0..1).map(|_|&c).collect();
| ^^^ - `c` is borrowed here
| |
| may outlive borrowed value `c`
Is there a way to make it work?