Skip to content

Instantly share code, notes, and snippets.

@nyanpasu64
Last active November 30, 2020 10:05
Show Gist options
  • Save nyanpasu64/285ed17bb8787cf6821e900085c5c38b to your computer and use it in GitHub Desktop.
Save nyanpasu64/285ed17bb8787cf6821e900085c5c38b to your computer and use it in GitHub Desktop.
let mut v = vec![0; 10];
let a = &mut v;

// braces not necessary with NLL.
{
    // let b = a; // moves a, doesn't compile.
    let b = &mut *a; // stacked borrow of a, compiles.
}
*a = vec![];
struct MutRef<T>(T);

impl<T> MutRef<&mut T> {
    fn stack(&mut self) -> MutRef<&mut T> {
        // &mut self is required.
        MutRef(&mut *self.0)
    }
}

fn main() {
    let mut x = 1i32;
    // mut is required. This is the only downside over a naked &mut.
    let mut r = MutRef(&mut x);
    {
        let r2 = r.stack();
    }
    drop(r);
}

wonder if you can easily stack-borrow a struct holding a &mut (you can't make it impl Clone) right now i'm using &Struct<&mut Buffer> and that's just sad in a Java way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment