Understanding Rust syntax in Guessing Game


I am working through the example code in the Rust Book and I saw these code snippets.

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,


match guess.cmp(&secret_number) {
    Ordering::Less => println!("Too small!"),
    Ordering::Greater => println!("Too big!"),
    Ordering::Equal => {
        println!("You win!");

In the first "match", parse's curly braces end with a semi colon but in the second "match", cmp's curly braces do not.

Why is there such a difference? If I will know this later in the chapters, then I apologize for posting it too early.

This is the difference between statement and expression.

Every match is an expression. That means, you can write

let x = match some_expression {
    // snip

(as in the first example) or

fn something() {
    // snip
    match some_expression {
        // snip

(that's what seems to be in the second example). In other words, you can treat the match block as some value. So, let's replace it with something simpler, so that the match syntax won't distract us: let's speak about literal 0.
The first case will then be let guess: u32 = 0; The second one is just 0.

The formal difference is that let begins a statement of the form let *var*: *type* = *expression*; and the semicolon is a part of this statement syntax (or, more generally, of any statement syntax, AFAIK). The second case, contrary to this, is just a bare expression, without any enclosing statement; and the expression doesn't need any punctuation around it.

1 Like

Hi @Cerberuser

Thanks for the prompt reply. I understand that now.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.