Stream: t-lang/wg-unsafe-code-guidelines

Topic: borrowing fields mutably from raw pointer receiver


Matias Rodriguez (Nov 04 2019 at 22:40, on Zulip):

I am wondering whether this toy example is intended to work(it works fine in MIRI),I am currently relying on this not being UB:

struct Foo{
    a:String,
    b:Vec<u32>,
}

unsafe fn borrow_field_a<'a>(this:*mut Foo)->&'a mut String{
    &mut (*this).a
}

unsafe fn borrow_field_b<'a>(this:*mut Foo)->&'a mut Vec<u32>{
    &mut (*this).b
}

fn main(){
    let mut foo=Foo{
        a:"hello".into(),
        b:vec![0,1,2],
    };

    let mut ptr=&mut foo as *mut Foo;

    let a=unsafe{ borrow_field_a(ptr) };
    let b=unsafe{ borrow_field_b(ptr) };
}
Last update: Nov 20 2019 at 12:55UTC