#Move semantics in block expressions

9 messages · Page 1 of 1 (latest)

shrewd lantern
#

Why does the borrow checker allow the following expression:

struct A([i32;3]);
fn main() {
    let var_498 = A([1,2,3]);
    let x = {var_498.0}[{
        var_498;
        1
    }];
    println!("{}", x)
}

but disallow

struct A([i32;3]);
fn main() {
    let var_498 = A([1,2,3]);
    let x = var_498.0[{
        var_498;
        1
    }];
    println!("{}", x)
}
solemn moss
#

Uh, what error does the latter give you?

#

What's the output of cargo check?

shrewd lantern
#
--> run_874_manual.rs:4:13
  |
3 |       let var_498 = A([1,2,3]);
  |           ------- move occurs because `var_498` has type `A`, which does not implement the `Copy` trait
4 |       let x = var_498.0[{
  |  _____________^
5 | |         var_498;
  | |         ------- value moved here
6 | |         1
7 | |     }];
  | |______^ value used here after move
#

The code is just in an individual .rs file and not in a package

solemn moss
#

Ah, I see.

In the former snippet, you make a copy of var_498.0. This is because it's the return value of a block, so it's moved, and its type is Copy, so its copied instead. Then, you run the block expression inside the [].

In the second snippet, you first borrow var_498.0 (implicitly, as part of how [] works), which borrows var_498. Then, you try to move var_498 into the inner block, while it's still borrowed.

shrewd lantern
#

I see, so the index expression works by first borrowing var_498 in the block statement within the index expression. Then it attempts to borrow var_498.0 if it's a place expression and if it's a block statement then it makes a copy. The index expression makes a copy the result into x and then var_498.0's ownership is returned?

visual wadi
#

it's not about the index expression

#

whenever you use a block expression {x} this prohibits x being used as a place, and forces it to be moved instead