Why is mutably borrowing the same object twice disallowed in a single statement?

Here an example:

Changing the call line to:

let tmp = f.bar(1)

fixes the problem, but it will heavily affect the usability of my solution (having many nested levels of this).
Are the two code snippets not semantically identical?

I'll also mention that the result of the method is Copy in my code as well, holding no reference to the struct.

1 Like

The statement is evaluated left to right. Imagine that f in the expression f.bar() is a method call instead, like get_f().bar(get_f().bar(1)). You can see that a second get_f() is called after the first get_f().

In Rust this f. is not a syntactic detail. It is evaluated as an action of taking an exclusive reference, so the exclusive reference is taken first, before Rust looks at the arguments.

The one-liner runs: get_f(); get_f(); bar(); bar();
The two-line version runs get_f(); bar(); get_f(); bar();

So introduction of a variable is a fine way to solve the issue.


Thanks for the explanation!

Seems like this is a fine way to solve this (for anyone looking into it in the future):

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.