jpernst / rental

Rust macro to generate self-referential structs
Apache License 2.0
211 stars 11 forks source link

Stuck: how do I use borrow()? #13

Closed MarkSwanson closed 7 years ago

MarkSwanson commented 7 years ago

At the end of some unit of work I must have mutable access to other fields of the struct, but I can only figure out how to get access to the suffix via rent*(). Example:

        #[rental_mut]
        pub struct RentContextWrite2 {
            message_builder: Box<message::Builder<SAW>>,
            point_builder: point::Builder<'message_builder>,
        }

I need mutable access to message_builder. If I do: let ctx = RentContextWrite2::new() {... }; let x = unsafe {rent_context_write2.borrow()}; saw.emb(x.message_builder);

I just get: error: field message_builder of struct rent_point::RentContextWrite2_Borrow is private

Is there any way to get access to message_builder?

Thanks!

jpernst commented 7 years ago

No. A mutable borrow of message_builder is already held by point_builder. Producing another mutable borrow would be a violation of rust's borrowing semantics, and thus undefined behavior. If you need access to message_builder, the only well-defined way for that to be done is if such access is provided through some API on point_builder, since it's the one that holds the mutable borrow.

MarkSwanson commented 7 years ago

Got it. Just a fyi - after playing with various ways to lay things out I successfully was able to get access to message_builder using ctx.into_head(). I'm so happy you created into_head() ! It turns out that I wanted to drop the suffix and access the head so I can close things properly (not something I could RAII).

Self-referential structs are hard in Rust. Thanks a ton for creating Rental - it helps a lot.