Why does the compiler need an implementation of a trait to call a default free function?

前端 未结 2 1062
野的像风
野的像风 2021-01-25 22:47

When calling a default implementation on a trait which does not take self, why does it neeed an implementing type to be annotated?

A minimal, reproducible ex

相关标签:
2条回答
  • 2021-01-25 23:23

    This is not only a default implementation but the very specific case in which this default implementation does not even mention Self/self in its parameters, result and body.

    I find much more easy to understand a rule saying that a type is required every time we use a trait, in any case, rather that « except if the default implementation does not even mention Self/self in its parameters, result and body ».

    For this very specific use case, where you do not want to explicitly name a type when calling the function you need, I suggest using a free function.

    mod builder {
        // ...
        pub fn make_default() -> Simple {
            Simple
        }
        // ...
    }
    
    pub fn main() {
        let _ = builder::make_default();
    }
    
    0 讨论(0)
  • 2021-01-25 23:31

    Provided methods in Rust are not like static methods in Java. Even a function with no arguments and a default implementation can be overridden by implementors. Consider adding another type that implements Builder but overrides the new function:

    struct Noisy {}
    
    impl builder::Builder for Noisy {
        fn new() -> builder::Simple {
            println!("Ahahahah I'm creating a Simple!!!11!");
            builder::Simple
        }
    }
    
    fn main() {
        // wait, should this call builder::Simple::new() or Noisy::new()?
        let _ = builder::Builder::new();
    }
    

    If you want the effect of a Java static function that always has the same behavior, you should use a free function, as prog-fh's answer also suggests.

    0 讨论(0)
提交回复
热议问题