Why '-> &mut i32' '-> &i32' so different in this?

#1

like:

fn foo1(i: &mut i32) -> &i32 {
    i
}
fn foo2(i: &mut i32) -> &mut i32 {
    i
}

then use ‘rustc your_rust.rs --emit mir’

you will get:

fn foo1(_1: &mut i32) -> &i32{
    let mut _0: &i32;                   
    bb0: {                              
        _0 = _1;                        
        return;                   
    }
}
fn foo2(_1: &mut i32) -> &mut i32{
    let mut _0: &mut i32;               
    let mut _2: &mut i32;
    bb0: {                              
        StorageLive(_2);        
        _2 = _1;                     
        _0 = _2;                    
        StorageDead(_2);             
        return;                   
    }
}

I don’t understand, why not:

fn foo2(_1: &mut i32) -> &mut i32{
    let mut _0: &mut i32;               
    bb0: {                                   
        _0 = _1;                    
        return;                    
    }
}
0 Likes

#2

Try running rustc with -Zmir-opt-level=3 - I don’t think the optimizations are turned on by default.

2 Likes

#3

As for why the code is different in the first place: & is copyable, but &mut is not. Places which appear to copy &mut create a new borrow behind the scenes.

5 Likes

#4

Curious why you’re looking at MIR for this? Is it just educational? Assembly will be the same, even at opt-level=0

2 Likes

#5

thx, anyway.

0 Likes

#6

:+1: I tried it, solved it, thx.

0 Likes