|
So, normally in Rust, it's no problem to ignore the return value of a function. However, some types are tagged with the `#[must_use]` attribute, which makes it a warning at compile time to ignore the return value of any function that returns that type. Take the following program, which writes a buffer of bytes directly to stdout: fn main() {
let mut out = std::io::stdout();
out.write([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21]);
}
The `.write()` method returns a Result type. The output of compiling this program: $ rustc pxtl.rs
pxtl.rs:3:5: 3:53 warning: unused result which must be used, #[warn(unused_must_use)] on by default
pxtl.rs:3 out.write([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21]);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Again, it's just a warning, so the program will compile and run as expected: $ ./pxtl
Hello!
If you really don't care about the return value here, the simplest (and probably best) way of appeasing this warning is to explicitly ignore the return type by making use of pattern matching: fn main() {
let mut out = std::io::stdout();
let _ = out.write([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21]);
}
In Rust, the underscore is a pattern that means "I don't care about this thing, completely ignore it". The advantage of using the underscore here rather than an actual variable, e.g. `let x = out.write(...)`, is that it will be impossible to refer to the return value later on and thus explicitly expresses your intent to ignore it. (Furthermore, if you assigned the return value to a variable and then didn't use it later on, Rust would emit yet another warning, this time for having an unused variable.)The warning message alludes to a second way of silencing this error, which is by sticking the `#[allow(unused_must_use)]` attribute on top of your function. This will silence any warnings that arise from that function. If you wanted to disable this warning for your entire program, you could instead stick the `#![allow(unused_must_use)]` global attribute at the top of your program. Alternatively, you could compile the program with the `--allow unused_must_use` flag to completely silence all warnings of this type. (One final note: in all cases where you see word "allow" used above, if you replace it with "deny" it will turn the warning into a compile-time error, thus enabling you to enforce a more rigorous error-handling strategy if you so choose.) |