What is the proper way to use GhostCell and GhostToken?

Hello.
In the past few days, I noticed that there is an alternative of RefCell in Rust to acquire the mutable reference of the immutable object, called GhostCell. The paper GhostCell: Separating Permissions from Data in Rust had proven the safety of this method.
However, I found it is difficult for me to use the GhostCell in the production because GhostCell requires:

The closure must be variant over the lifetimes.
None of the branded items can be returned by the closure.

This means that I cannot:

Create a GhostCell out of the closure. When I want to change its value, I create a closure by GhostToken and acquire the mutable reference in this closure.
Create a GhostCell in the closure and return it for other usages.

For example, if I have a vector in the reference counter, such as Rc::new(vec![1,2,3]), how can I acquire the mutable reference of vec![1,2,3]? I tried to create Rc::new(GhostCell::new(vec![1,2,3])) and acquire it mutable reference by GhostToken::new(|mut token|{...}), but the 'token' will escape the closure body, which is not allowed.

Could anyone tell me what is the proper way to use GhostCell? Thanks so much!

It could look something like this

use std::rc::Rc;
use ghost_cell::{GhostToken,GhostCell};
let val = GhostToken::new(|mut tok| {
    let cell = GhostCell::new(vec![1,2,3]);
    let rc = Rc::new(&cell);
    let rc2 = Rc::clone(&rc);
    rc.borrow_mut(&mut tok).push(4);
    rc2.borrow_mut(&mut tok).push(5);
    // Return vec
    cell.into_inner()
});
println!("{:?}",val)
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.