0

This is the code I have:

use std::fs::File;

const INPUT_FILE_PATH: &str = "./data/input";

fn main() {
    let file = match File::open(INPUT_FILE_PATH) {
        Ok(file) => file,
        Err(error) => println!("Error opening input file: {}", error),
    };
}

When I run cargo run, I get the following error:

error[E0308]: `match` arms have incompatible types
 --> src/main.rs:8:23
  |
6 |       let file = match File::open(INPUT_FILE_PATH) {
  |  ________________-
7 | |         Ok(file) => file,
  | |                     ---- this is found to be of type `File`
8 | |         Err(error) => println!("Error opening input file: {}", error),
  | |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `File`, found `()`
9 | |     };
  | |_____- `match` arms have incompatible types
  |

I don't understand the error message. I found out by accident that if I change the println! to panic! the program compiles without problems, but I can't for the life of me understand why println! doesn't work.

Why is it that println! gives an error, when panic! doesn't?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Dennis
  • 1
  • 1
    What is the value of `file` when the error branch is taken? (followup to what answer I suspect you might provide) Why do you think that? (followup to what answer I suspect you might provide) Is that value possible in Rust? – Shepmaster Dec 09 '20 at 21:38
  • 1
    It looks like your question might be answered by the answers of [Why would I use divergent functions?](https://stackoverflow.com/q/31082098/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Dec 09 '20 at 21:40
  • 1
    Oh, the compiler is complaining about `file` being a () if the error route is taken. I thought the error was about `error` being a (). Thanks for the help @Shepmaster (feel free to write an answer if you'd like me to accept this) – Dennis Dec 09 '20 at 21:46
  • 1
    Yep! And `panic!` works because the compiler knows that control will never return once it's called (it's a diverging function) so the type can be effectively anything. – Shepmaster Dec 09 '20 at 21:56

0 Answers0