must_use Warns On Discarded Returns
Annotating helper functions with #[must_use] turns ignored return values into unused_must_use warnings, while let _ = marks deliberate discard.
Code
// must_use:返回值被丢弃时编译器发 unused_must_use 警告
#[must_use = "parse failures are silently swallowed; check the returned Option"]
fn parse_tag(raw: &str) -> Option<&str> {
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
}
fn main() {
// 正常用法:绑定返回值,无警告
let tag = parse_tag(" core ");
println!("tag: {tag:?}");
// 忽略返回值:编译期警告,不是 panic,程序照常运行
parse_tag(" ");
// 故意丢弃:let _ = 前缀把意图写明
let _ = parse_tag("");
println!("done");
}How it works
Count the functions parse_tag and main as the entire surface area of must_use Warns On Discarded Returns.
What to watch for
- No external surface: all behavior comes from the standard library.
Using it
One line captures it: fn parse_tag(raw: &str) -> Option<&str>
The file announces its steps in the output: tag:, done.
main calls 1 helper in sequence: parse_tag.
Key statements
fn parse_tag(raw: &str) -> Option<&str> {
let trimmed = raw.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
}
Interactive Tools for This Topic
FAQ
- What does must_use Warns On Discarded Returns print when run?
- The script runs standalone; its 2 labeled outputs include `tag:`, `done`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.