是否可以在特征中具有构造函数? [英] Is it possible to have a constructor function in a trait?

查看:40
本文介绍了是否可以在特征中具有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 trait 中寻找构造函数的例子,但运气不佳.这是在 Rust 中惯用的做法吗?

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?

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

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

fn main() {
    println!("message")
}

<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

强制转换会返回与 core::marker::Sized 相关的错误.

Casting this returns a core::marker::Sized related error.

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

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

fn main() {
    println!("message")
}

<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

推荐答案

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

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
}

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

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

这篇关于是否可以在特征中具有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆