Assignment without the let keyword

I was trying to learn the difference between let _ = f(); and _ = f();, but I couldn't find documentation for assignment without the let keyword.

Are they equivalent code? Where is it documented?

_ = EXPR is documented: Underscore expressions - The Rust Reference, which is similar to a wildcard pattern.
The underscore expression page provides this snippet:

// unused result, assignment to `_` used to declare intent and remove a warning
_ = 2 + 2;
// triggers unused_must_use warning
// 2 + 2;

// equivalent technique using a wildcard pattern in a let-binding
let _ = 2 + 2;

So they’re equivalent.

Note that let _ = ... and let _name = ... are not the same. Binding to _ drops the expression immediately, while binding to a _name will drop the expression at the end of scope. (This is a very important distinction for lock guards).

5 Likes

it seems no difference (in asm code )
here is code

//1.rs
fn main(){
    let _ = f();
}
fn f(){

}

here is asm code

//1.asm 
[0x00006920]> pdf
            ; DATA XREF from main @ 0x6947(r)
β”Œ 8: sym._1::main::h526e3d181a20c5ce ();
β”‚ rg: 0 (vars 0, args 0)
β”‚ bp: 0 (vars 0, args 0)
β”‚ sp: 0 (vars 0, args 0)
β”‚           0x00006920      50             push rax                    ; _1::main::h526e3d181a20c5ce
β”‚           0x00006921      e80a000000     call sym _1::f::hf752b26401dbd083 ; sym._1::f::hf752b26401dbd083
β”‚           0x00006926      58             pop rax
β””           0x00006927      c3             ret

Here is for 2.rs

//2.rs
fn main(){
     _ = f();
}
fn f(){

}

and asm code

//2.asm
          ; DATA XREF from main @ 0x6947(r)
β”Œ 8: sym._2::main::h3d6467ec21e25939 ();
β”‚ rg: 0 (vars 0, args 0)
β”‚ bp: 0 (vars 0, args 0)
β”‚ sp: 0 (vars 0, args 0)
β”‚           0x00006920      50             push rax                    ; _2::main::h3d6467ec21e25939
β”‚           0x00006921      e80a000000     call sym _2::f::h286670354a45964b ; sym._2::f::h286670354a45964b
β”‚           0x00006926      58             pop rax
β””           0x00006927      c3             ret

it seems the same
i guess 'let _ ' and ' _ ' both tells rustc do not store the return value to rax

1 Like