3 ms·
Not quite. Try this: import "os" func main() { os.Open("this file does not exist") } This will compile just fine, producing no compiler erro
by bascule 9y ago
Not quite. Try this:
import "os"
func main() {
os.Open("this file does not exist")
}
This will compile just fine, producing no compiler error or warnings whatsoever. The error is just silently ignored.
Compare to Rust:
use std::fs::File;
fn main() {
File::open("this file does not exist");
}
This will produce the following warning:
warning: unused result which must be used
--> test.rs:14:5
|
14 | File::open("this file does not exist");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_must_use)] on by default
This example is a bit contrived, because if you open a file you probably want to do something with it. But imagine something where the only return value you care about is the error, like say "txn.commit()"
- mbel 9y agoA slightly related note: you can get similar behavior in C (and C++) with compiler extensions. In GCC and clang marking function with '__attribute__((warn_unused_result))' will produce a warning if function is called without using the result. Equivalent for MSVC is '_Check_return_'. Obviously this is not nearly as convenient as your Rust example, but enables some of its the benefits.
- gpderetta 9y agoC++17 has (will have?) [[nodiscard]] with the same semantics.