profile
viewpoint

Ask questionsif/while Some(n) = &mut foo sugar will leak a temporary mutable borrow to current scope in particular situation

Same Code in the Playground

pub struct Demo {
    foo: Option<Box<Demo>>,
}

// Compiles
pub fn foo1(mut a: &mut Demo) {
    if let Some(ref mut b) = a.foo {
        a = b;
    }
    a.foo = None;
}

// Does not compile
pub fn foo2(mut a: &mut Demo) {
    if let Some(b) = &mut a.foo {
        a = b;
    }
    a.foo = None;
}

// Same Error with foo2
pub fn foo3(mut a: &mut Demo) {
    if let Some(ref mut b) = &mut a.foo {
        a = b;
    }
    a.foo = None;
}

What is exactly difference between foo1 and foo2

ADD: I think foo1 will desuger something like this:

pub fn foo1_desugered(mut a: &mut Demo) {
    match a.foo {
        Some(ref mut _1) => a = _1 ,
        None => ()
    }
    a.foo = None;
}

and foo2 will be like:

pub fn foo2_desugered(mut a: &mut Demo) {
    let mut _t1 = &mut a.foo;
    match _t1 {
        Some(_1) => a = _1 ,
        None => ()
    }
    a.foo = None;
}

ADD#2 And if I explicit add a scope:

// Does not compile
pub fn foo2(mut a: &mut Demo) {
    {
        if let Some(b) = &mut a.foo {
            a = b;
        }
    }
    a.foo = None;
}

pub fn foo2_desugered(mut a: &mut Demo) {
    {
        let mut _t1 = &mut a.foo;
        match _t1 {
            Some(_1) => a = _1 ,
            None => ()
        }
    }
    a.foo = None;
}

same error :(

rust-lang/rust

Answer questions ExpHP

But phrasing it that way makes it sound like a bug in match ergonomics.

useful!

Related questions

Spurious NaNs produced by trig functions with valid inputs on Windows GNU toolchains hot 3
using 'cargo install xsv' on windows 10 triggers rustc internal error hot 2
under latest MinGW, cannot link with C code using stdout hot 2
Archive all nightlies hot 2
chain() make collect very slow hot 1
build an empty project failed (undefined reference to `__onexitbegin') hot 1
Invalid collision with TryFrom implementation? hot 1
Crater runs for Rust 1.38.0 hot 1
Spurious NaNs produced by trig functions with valid inputs on Windows GNU toolchains hot 1
Building LLVM with Clang fails hot 1
Internal compiler error: can't buffer lints after HIR lowering hot 1
E0373 help suggests `move async` but the correct syntax is `async move` hot 1
Tracking issue for `Option::contains` and `Result::contains` hot 1
async fn + rustfmt don't "just work" inside of RLS hot 1
Include images in rustdoc output hot 1
source:https://uonfu.com/
Github User Rank List