struct Foo {
elem1: u32,
elem2: String,
}
fn demo1(x: &mut Foo) {
let ref_1 = &mut x.elem1;
let ref_2 = &mut x.elem2;
let ptr_x = x as *mut Foo; // Ok!
}
fn demo2(x: &mut Foo) {
let ref_1 = &mut x.elem1;
while *ref_1 < 20 {
let ptr_x1 = x as *mut Foo; // Failed: cannot borrow *x as mutable more than once at a time
// let ptr_x2 = std::ptr::addr_of_mut!(x); // Failed: cannot borrow x as mutable more than once at a time
// let ptr_x3 = std::ptr::addr_of_mut!(*x); // Failed: cannot borrow *x as mutable more than once at a time
}
}
struct Foo {
elem1: u32,
elem2: String,
}
fn demo1(x: &mut Foo) {
let ref_1 = &mut x.elem1;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
// .. forever
}
if you do only this you will see that it does not work
struct Foo {
elem1: u32,
elem2: String,
}
fn demo1(x: &mut Foo) {
let ref_1 = &mut x.elem1;
if *ref_1 < 20 { return }
let ptr_x = x as *mut Foo;
if *ref_1 < 20 { return }
}
ref_1 mutably borrows x, so x is unusable until ref_1 expires. ref_1 expires only when the loop exists, so you can't use x until then