What are the curly braces in "&{ s }.borrow_self()" for?
I'm going through the statements and expressions chapter in the Rust book. What are the curly braces in &{ s }.borrow_self()
for?
Am I getting the pointer, and if so would it not make more sense to use &s.borrow_self()
?
Just a little confused as to what purpose the curly braces have and the logic behind using them.
#![allow(unused)]
fn main() {
struct Struct;
impl Struct {
fn consume_self(self) {}
fn borrow_self(&self) {}
}
fn move_by_block_expression() {
let s = Struct;
// Move the value out of `s` in the block expression.
(&{ s }).borrow_self();
// Fails to execute because `s` is moved out of.
s.consume_self();
}
}
{}
creates a new scope. Remember that the last statement in each scope is used as the return value. In this case {s}
evaluates to s
. So &{s}
moves s
into the scope, returns it, and then just references it.
Let's evaluate "manually":
-
(&{s}).borrow_self()
=> Moves
to the new scope and return it. -
(&s).borrow_self()
=> References
-
Struct::borrow_self(&s)
=> Evaluate method over&self
(&s
)
Quoting the linked page from the reference:
This can be used to force moving a value if really needed. For example, the following example fails on the call to
consume_self
because the struct was moved out ofs
in the block expression.
So:
- In general, curly braces can be used when something needs to be moved for the code to be correct.
- In this example, their usage is explicitly stated to be incorrect. The valid code would contain just
s.borrow_self()
, as you've found out. - The value of this example is in providing the case when the move semantics are immediately obvious. It doesn't have to be useful as a code, since the quoted book is language reference, and it's more important for it to clearly show the expected semantics then to educate on "how the code should be written".