#[must_use] on associated function definition when trait declaration does not have it should still trigger warning when calling function concretely

e63d84a
Opened by Ryan Scheel at 2018-02-27 18:00:35

I expect the following code (Playpen) to emit a warning on the last line of main that the result of s.the_must_use_fn() must be used.

#![feature(fn_must_use)]

fn main () {
    let s = Struct;
    s.the_must_use_fn();
}

trait Trait {
    fn the_must_use_fn(&self) -> String;
}

struct Struct;

impl Trait for Struct {
    #[must_use]
    fn the_must_use_fn(&self) -> String { "".to_string() }
}

Ref #43302 as the tracking issue for this feature.

  1. I expect the following code (Playpen) to emit a warning on the last line of main that the result of s.the_must_use_fn() must be used.

    fn main () {
        let s = Struct;
        s.the_must_use_fn();
    }
    
    trait Trait {
        fn the_must_use_fn(&self) -> String;
    }
    
    struct Struct;
    
    impl Trait for Struct {
        #[must_use]
        fn the_must_use_fn(&self) -> String { "".to_string() }
    }
    

    Ref #43302 as the tracking issue for this feature.

    Martin Nordholts at 2023-10-05 18:23:40

  2. This is expected (or at least, known) behavior; the #[must_use] attribute needs to go on the function signature in the trait definition, not the implementation. I argue that the current behavior makes sense: the semantics of a trait method should be the same across implementations. We should document this better, though—thanks for starting on that!

    Zack M. Davis at 2018-02-23 23:33:25

  3. Then there should be a warning when #[must_use] is on a trait method.

    But while it is known behavior, I didn't expect it. I expect that concretely calling a trait method should work the same as concretely calling an inherent method. Of course, when called generically, it should only look at the trait declaration.

    Ryan Scheel at 2018-02-23 23:58:03