6

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?

mcarton
  • 27,633
  • 5
  • 85
  • 95
Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114

1 Answers1

7

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

pyj
  • 1,489
  • 11
  • 19