Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I apply must_use to a function result?

Tags:

rust

I have a function that returns a f64. I'd like to ensure that the output from this function is used, rather than just ignored. Is there any way to do this?

The return type is not used for error handling so wrapping it in a Result or Option doesn't really make sense.

I'd like something similar to this:

#[must_use]
fn calculate_the_thing(number: f64) -> f64 {
    number * 2.0
}
like image 222
timlyo Avatar asked Apr 29 '16 12:04

timlyo


1 Answers

Not before Rust 1.27. In these versions, #[must_use] only applies to types, not individual values.

One alternative is to define a simple wrapper type that is #[must_use]:

#[must_use = "this value should be used (extract with .0)"]
pub struct MustUse<T>(pub T);

Your function can then return MustUse<f64>, and users will get a warning if they write calculate_the_thing(12.3), even suggesting the right way to get the thing they want: let x = calculate_the_thing(12.3).0;. For instance:

fn calculate_the_thing(number: f64) -> MustUse<f64> {
    MustUse(number * 2.0)
}

fn main() {
    calculate_the_thing(12.3); // whoops

    let x = calculate_the_thing(12.3).0;
    println!("{}", x);
}
warning: unused `MustUse` which must be used: this value should be used (extract with .0)
 --> src/main.rs:9:5
  |
9 |     calculate_the_thing(12.3); // whoops
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_must_use)] on by default
like image 168
huon Avatar answered Nov 14 '22 17:11

huon