4

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
  • 24,420
  • 5
  • 70
  • 79
Paul Razvan Berg
  • 10,820
  • 7
  • 50
  • 86

1 Answers1

5

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,470
  • 11
  • 19