Search code examples
rustsemicolon-inference

Why no semicolon after Ok(()) at the end of a function in rust?


Code snippet taken from the documentation on current_dir:

use std::env;

fn main() -> std::io::Result<()> {
    let path = env::current_dir()?;
    println!("The current directory is {}", path.display());
    Ok(())
}

I noticed that only by adding a semicolon after Ok(()), the program does not compile with the following error:

error[E0308]: mismatched types
expected enum `std::result::Result`, found `()`

Why is that?


Solution

  • Rust returns the value of the last expression. When you add the semicolon after Ok(()), the final expression becomes a statement, so it's returning the "value" of the statement, which is a lack of value, also called unit (known as "()").

    This question is also asked and answered here: Are semicolons optional in Rust?

    Expressions on rust documentation: https://doc.rust-lang.org/stable/rust-by-example/expression.html