Opening new block of code just to borrow_mut?

I am currently learning rust, which is painful process. Among others, currently trying to understand why we are using Rc,RefCell and other goodies.
I encountered such example (last example from std::rc - Rust):

fn main() {

    // Add the `Gadget`s to their `Owner`.
        let mut gadgets = gadget_owner.gadgets.borrow_mut();

        // `RefCell` dynamic borrow ends here.

   // snip

My question is:

  • is it common practice in Rust production grade code to open new block just to borrow_mut() something?

If the question doesn't make sense, sorry for inconvinience - still learning....


1 Like

You can also use drop(gadgets);. But the block, while more verbose, has the benefit of making it visually obvious which code is borrowing gadget_owner.gadgets — that's the scope in which you need to make sure not to call another function that might want to borrow gadget_owner.gadgets again.

Also note that a {} block just for this purpose is only necessary when there isn't any other block (like an if or a function's body) that is already an appropriate scope.


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.