I am doing some experimenting with rust and running into some issues. What I am trying to do is allocate a String struct on the heap (not just the buffer) and hold a reference to that even after the object has been leaked. Then deref that pointer back into the string. The point of this is I am looking at implementing a simple garbage collector for a project and I need to have something keep track of all the objects in the system even after nothing references them. So I would keep a array of pointers to all the objects and then do the normal mark and sweep pass.
However I cannot seem to find a way to get a raw pointer to the String without consuming the Box (which I don't want to do, because other code needs to use this Box). When I try the code below I get the error non-primitive cast: std::string::String as *mut std::string::String. I know this not-idiomatic rust (and very unsafe), but any help would be appreciated.
fn main() {
let before = Box::new("foo".to_string());
let ptr = *before as *mut _; // can't get raw pointer here
println!("before = {}", *before); // Still want to access box value here
Box::leak(before); // memory is leaked
unsafe {
let after: String = *ptr; // can still access the string because we have the address.
println!("after = {}", after);
}
}