Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to declare functions that will warn on unused results in Rust? [duplicate]

Does Rust have a way to declare a function, where not using its result will warn - for any types?

Something like GCC's __attribute__((warn_unused_result));?

like image 606
ideasman42 Avatar asked Dec 30 '25 21:12

ideasman42


2 Answers

As of 1.27, #[must_use] works for functions too.


It appears that the #[must_use] attribute is only applicable to structs, enums and unions (union is not available in stable Rust yet, though): source. I think this means you can't override it for a function.

like image 155
ljedrz Avatar answered Jan 04 '26 12:01

ljedrz


Yes, if you don't mind wrapping said types.

The #[must_use] attribute, as answered by @ljedrz, only applies to types. However, in Rust, creating new types is painless and has not impact on performance. Therefore, just wrap your type in a MustUse<T> type, and have your function resolve this.

struct MustUse<T>(T);
like image 30
Matthieu M. Avatar answered Jan 04 '26 11:01

Matthieu M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!