Reputation: 105
See some code below:
#[derive(Debug)]
struct MyString {
a: String,
}
impl MyString {
fn new(s: &str) -> Self {
MyString { a: String::from(s) }
}
}
impl Deref for MyString {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.a
}
}
impl Drop for MyString {
fn drop(&mut self) {
println!("{} dropped!", self.a);
}
}
fn main() {
let mut test1 = MyString::new("test1");
let mut test1 = MyString::new(&test1);
println!("shadow variable test1");
test1.a = String::from("test2");
}
I thought there should be a compile error because test1 is still borrowed.
However, there's no compile error, and the result is
shadow variables test1
test2 dropped
test1 dropped
So if a variable is shadowed, the value is still valid in the current scope. But who is its owner?
Upvotes: 1
Views: 193
Reputation: 23264
From an ownership standpoint, your code is exactly equivalent to:
fn main() {
let mut test1_1 = MyString::new("test1");
let mut test1_2 = MyString::new(&test1_1);
println!("shadow variable test1");
test1_2.a = String::from("test2");
}
So test1_1
is dropped when it goes out of scope at the end of the main
function.
Note also that test1_2
does not borrow test1_1
, the borrow only lasts for as long as the call to MyString::new(&test1)
. Afterwards there is no connection between the two variables.
Upvotes: 1