#[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
.