Is it possible to have a constructor function in a trait?

前端 未结 1 1999
鱼传尺愫
鱼传尺愫 2020-12-20 13:31

I\'m trying to find examples for constructor functions in traits, but haven\'t had much luck. Is this a idiomatic thing to do in Rust?



        
相关标签:
1条回答
  • 2020-12-20 13:37

    You need to use the Self type. In trait declarations, Self refers to the type that implements a trait. In your case, the trait declaration should look as follows:

    trait A {
        fn new() -> Self; // Self stands for any type implementing A
    }
    

    Your original version is subtly different because it will return a trait object, not a value of the implementor type.

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