Rustling notes: mutable parameters

Using this website Compiler explorer explored mutable parameters. Another blog to explain the topic.

  • mutable reference
pub fn main() {
    let mut x = 5;
    plus_one(&mut x);
}

fn plus_one(x: &mut i32) {
    (*x) += 1;
}

The assembly code

example::main:
        push    rax
        mov     dword ptr [rsp + 4], 5
        lea     rdi, [rsp + 4]
        call    example::plus_one
        pop     rax
        ret

example::plus_one:
        sub     rsp, 24
        mov     qword ptr [rsp + 8], rdi
        mov     eax, dword ptr [rdi]
        inc     eax
        mov     dword ptr [rsp + 20], eax
        seto    al
        test    al, 1
        jne     .LBB1_2
        mov     rax, qword ptr [rsp + 8]
        mov     ecx, dword ptr [rsp + 20]
        mov     dword ptr [rax], ecx
        add     rsp, 24
        ret
.LBB1_2:
        lea     rdi, [rip + str.0]
        lea     rdx, [rip + .L__unnamed_1]
        mov     rax, qword ptr [rip + core::panicking::panic@GOTPCREL]
        mov     esi, 28
        call    rax
        ud2

.L__unnamed_2:
        .ascii  "/app/example.rs"

.L__unnamed_1:
        .quad   .L__unnamed_2
        .asciz  "\017\000\000\000\000\000\000\000\007\000\000\000\005\000\000"

str.0:
        .ascii  "attempt to add with overflow"
  • mutable parameter ("In fact, moving-into-mutable is something that can happen even without a function call."):
pub fn main() {
    let x = 5;
    plus_one(x);
}

fn plus_one(mut x: i32) {
    x += 1;
}
example::main:
        push    rax
        mov     edi, 5
        call    example::plus_one
        pop     rax
        ret

example::plus_one:
        push    rax
        mov     dword ptr [rsp + 4], edi
        mov     eax, dword ptr [rsp + 4]
        inc     eax
        mov     dword ptr [rsp], eax
        seto    al
        test    al, 1
        jne     .LBB1_2
        mov     eax, dword ptr [rsp]
        mov     dword ptr [rsp + 4], eax
        pop     rax
        ret
.LBB1_2:
        lea     rdi, [rip + str.0]
        lea     rdx, [rip + .L__unnamed_1]
        mov     rax, qword ptr [rip + core::panicking::panic@GOTPCREL]
        mov     esi, 28
        call    rax
        ud2

.L__unnamed_2:
        .ascii  "/app/example.rs"

.L__unnamed_1:
        .quad   .L__unnamed_2
        .asciz  "\017\000\000\000\000\000\000\000\007\000\000\000\005\000\000"

str.0:
        .ascii  "attempt to add with overflow"