Getting around mutable borrows

fn do_something(obj:&mut Type)
fn do_something_1(obj:&mut Type)

fn main()
do_something_1(obj);//error,  cannot borrow `*obj` as mutable more than once at a time

Clearly the second time I call the do_something fn, the first borrow is being "freed", so I am not borrowing it anymore. How to structure that code so I can call those functions ?

Your example is too minimal.


Yep, but even after I've fixed it, it unfortunately still compiles...
For some reason in my code if I return &str instead of String, it complains about double borrow.
Anyway, forget about it. I've fixed it by returning String.
Thanks for taking interest.

If you return s: &str which is a part of obj, then obj is still borrowed by s. do_something_1 might modify obj thus modify what s references, So you cannot use s after calling it.

If returned s: &str is not a part of obj, then you should indicate it from the function signature by manually decorating lifetimes.

And lastly, if your API can return a &str without a problem, do not change the return type to String just to remove borrow checking error. Instead, call .to_string() at callsite like do_something(&mut obj).to_string(). This give the caller a choice to not allocate a new String when it's not needed.

1 Like

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.