|
| 1 | +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +#![feature(fn_must_use)] |
| 12 | +#![warn(unused_must_use)] |
| 13 | + |
| 14 | +struct MyStruct { |
| 15 | + n: usize, |
| 16 | +} |
| 17 | + |
| 18 | +impl MyStruct { |
| 19 | + #[must_use] |
| 20 | + fn need_to_use_this_method_value(&self) -> usize { |
| 21 | + self.n |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +trait EvenNature { |
| 26 | + #[must_use = "no side effects"] |
| 27 | + fn is_even(&self) -> bool; |
| 28 | +} |
| 29 | + |
| 30 | +impl EvenNature for MyStruct { |
| 31 | + fn is_even(&self) -> bool { |
| 32 | + self.n % 2 == 0 |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +trait Replaceable { |
| 37 | + fn replace(&mut self, substitute: usize) -> usize; |
| 38 | +} |
| 39 | + |
| 40 | +impl Replaceable for MyStruct { |
| 41 | + // ↓ N.b.: `#[must_use]` attribute on a particular trait implementation |
| 42 | + // method won't work; the attribute should be on the method signature in |
| 43 | + // the trait's definition. |
| 44 | + #[must_use] |
| 45 | + fn replace(&mut self, substitute: usize) -> usize { |
| 46 | + let previously = self.n; |
| 47 | + self.n = substitute; |
| 48 | + previously |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +#[must_use = "it's important"] |
| 53 | +fn need_to_use_this_value() -> bool { |
| 54 | + false |
| 55 | +} |
| 56 | + |
| 57 | +fn main() { |
| 58 | + need_to_use_this_value(); |
| 59 | + |
| 60 | + let mut m = MyStruct { n: 2 }; |
| 61 | + m.need_to_use_this_method_value(); |
| 62 | + m.is_even(); // trait method! |
| 63 | + |
| 64 | + m.replace(3); |
| 65 | + |
| 66 | + 2.eq(&3); |
| 67 | + |
| 68 | + // FIXME: operators should probably be `must_use` if underlying method is |
| 69 | + 2 == 3; |
| 70 | +} |
0 commit comments