Hyunsoo
Hyunsoo

Reputation: 139

Why can I assign a type that doesn't implement Copy from an inner scope to a mutable variable in an outer scope?

#[derive(Debug)]
struct MyStruct {
    a: u32,
    b: String,
}

fn main() {
    let mut s;
    {
        let _s = MyStruct {
            a: 1,
            b: "hello".to_string(),
        };
        //s = &_s;   // Error
        s = _s;      // Not an error
    }
    println!("{:?}", s);
}

The commented line is an error since the variable s would be a dangling pointer. However, I don't understand why s = _s; is not an error.

_s is created on the stack and dropped before the println macro is called. I didn't specify the Copy bound for MyStruct. I'm confused whether the variable s is pointing to the dangling pointer or copied from _s. The former can't be true since the compiler error didn't appear and the latter case is not understandable because I didn't implement Copy for MyStruct.

Upvotes: 2

Views: 85

Answers (1)

I think it is clear to you why &_s can't be used when the scope _s is defined leaved. Your question is why the other works.

In Rust, if a type implements the Copy trait, a statement like a=b will do a bitwise copy of b that will be accessible by a. After that, there will be two copies of the same object. If it is not a Copy type, then it will be moved into a. However, it is not necessarily a memory move operation taking place under the hood as it may stay in the same place in the stack, but this is not relevant to understand this question.

After the move, the object is bound to the new variable s, and the scope that s is defined is relevant from then on.

Note: You don't need s to be mutable for this because the s = _s; line is not an assignment but initialization.

Upvotes: 2

Related Questions