是否可以在特征中使用构造函数?

6D6*_*D65 8 rust

我试图在特征中找到构造函数的例子,但运气不好.这是Rust的惯用之处吗?

trait A {
    fn new() -> A;
}

struct B;
impl A for B {
    fn new() -> B {
        B
    }
}

fn main() {
    println!("message")
}
Run Code Online (Sandbox Code Playgroud)
<anon>:7:8: 9:9 error: method `new` has an incompatible type for trait: expected trait A, found struct `B` [E0053]
<anon>:7        fn new() -> B {
<anon>:8          B
<anon>:9        }
<anon>:7:8: 9:9 help: see the detailed explanation for E0053
error: aborting due to previous error
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)

转换它会返回core :: marker :: Sized相关错误.

trait A {
    fn new() -> A;
}

struct B;
impl A for B {
    fn new() -> A {
        B as A
    }
}

fn main() {
    println!("message")
}
Run Code Online (Sandbox Code Playgroud)
<anon>:8:10: 8:16 error: cast to unsized type: `B` as `A`
<anon>:8          B as A
                  ^~~~~~
<anon>:8:10: 8:11 help: consider using a box or reference as appropriate
<anon>:8          B as A
                  ^
<anon>:7:20: 7:21 error: the trait `core::marker::Sized` is not implemented for the type `A + 'static` [E0277]
<anon>:7        fn new() -> A {
                            ^
<anon>:7:20: 7:21 note: `A + 'static` does not have a constant size known at compile-time
<anon>:7        fn new() -> A {
                            ^
error: aborting due to 2 previous errors
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)

fjh*_*fjh 10

您需要使用该Self类型.在特征声明中,Self指的是实现特征的类型.在您的情况下,特征声明应如下所示:

trait A {
    fn new() -> Self; // Self stands for any type implementing A
}
Run Code Online (Sandbox Code Playgroud)

您的原始版本略有不同,因为它将返回特征对象,而不是实现者类型的值.