3 ms·
Is it though? Does the compiler not compile when you don't check / use the error result?
by Thaxll 7y ago
Is it though? Does the compiler not compile when you don't check / use the error result?
- kccqzy 7y agoIf you don't use the result, how would you be able to get the handle that represents the open file?
- inferiorhuman 7y agoYou wouldn't. In this case a more likely example would be writing to the file. You don't have to check the return value (in C or Rust) to do something useful, but you should. In Rust you'll get a warning (or error depending on how your workspace is setup). In C, you won't get anything. It's also worth noting that the Result enum can be and is used for things beyond file I/O.
- andolanra 7y agoIf you were to open a file that didn't exist and then not use the result at all, then you get a warning (which can be made an error, if you want): File::open("foo"); // warning: unused `Result` that must be used But that's also not necessarily an invalid program, it's just not a very useful one. Failing to open a file doesn't interrupt the program in any way, so File::open here will return either a file handle or an error, neither of which get used. However, if you open a file, don't check for an error, but still try to use the file, then your program won't compile: File::open("foo").read(&mut buffer); // error: method `read` not found in `Result<File, Error>` You need to be explicit about what to do in case the file didn't open, and Rust won't let you use your file handle unless you explicitly indicate what to do in that error case!