4 ms·
You should probably have read the rest of the blog post, because in Rust it is a compiler error to not test the result, and the post specifically calls this out
by andolanra 7y ago
You should probably have read the rest of the blog post, because in Rust it is a compiler error to not test the result, and the post specifically calls this out. Specifically, look for this section:
let mut my_file = MyFile::open(path)?;
// Note the `?` above. It's a simple operator that asks
// the compiler to check whether the operation succeeded.
// The *only* way to obtain a `MyFile` object is to
// have a successful `MyFile::open`.
// At this line, `my_file` is a `MyFile`, which means
// that we may use it.
- Thaxll 7y agoIs 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!