Reputation: 875
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();
}
}
Upvotes: 0
Views: 634
Reputation: 10237
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:
s.borrow_self()
, as you've found out.Upvotes: 3
Reputation: 42746
{}
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()
=> Move s
to the new scope and return it.(&s).borrow_self()
=> Reference s
Struct::borrow_self(&s)
=> Evaluate method over &self
(&s
)Upvotes: 4