为什么特征不能构建自身? [英] Why can a trait not construct itself?

查看:39
本文介绍了为什么特征不能构建自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码给了我一个编译错误:

This code give me a compilation error:

trait IBoo {
    fn new() -> Box<IBoo>;
}

虽然这段代码编译没有任何错误:

while this code compiles without any error:

trait IBoo {
    //fn new() -> Box<IBoo>;
}

trait IFoo {
    fn new() -> Box<IBoo>;
}

  1. 为什么第一个不能编译?rustc --explain E0038 没有直接提示我为什么不可能.
  2. 是否可以在一个接口(特征)中结合构造和方法?
  1. Why does the first one not compile? rustc --explain E0038 does not give me a direct hint why it is not possible.
  2. Is it possible to combine construction and methods in one interface (trait)?

推荐答案

编译器会告诉您这不起作用的确切原因:

The compiler tells you the exact reason this doesn't work:

error[E0038]: the trait `IBoo` cannot be made into an object
 --> src/main.rs:2:5
  |
2 |     fn new() -> Box<IBoo>;
  |     ^^^^^^^^^^^^^^^^^^^^^^ the trait `IBoo` cannot be made into an object
  |
  = note: method `new` has no receiver

注意最后一行.它告诉您错误的原因是 new() 不依赖于具有实现 IBoo 特征的值的实例.

Note the last line. It's telling you that the reason for the error is that new() doesn't depend on having an instance of a value implementing the IBoo trait.

通过不使用指向self 的某种指针,方法不能被动态调度调用.如果它不能被动态调度调用,这意味着它不能进入​​ trait 的关联 vtable.必须有一个关联的虚表,因为这就是Box 工作之类的东西.前段时间,核心 Rust 开发人员决定,即使在 trait 中包含一个单个非对象安全"方法,也会使整个 trait 失去用作对象的资格.

By not taking a pointer of some kind to self, the method cannot be invoked by dynamic dispatch. If it can't be invoked by dynamic dispatch, this means it cannot go into the trait's associated vtable. There has to be an associated vtable, because that's how something like Box<IBoo> works. Some time ago, the core Rust developers decided that including even a single "non-object safe" method in a trait disqualified the whole trait from being used as an object.

换句话说:因为你定义了一个不能动态分派的方法,IBoo trait 作为一个整体被取消了与动态一起使用的资格发送.

To put it in other words: because you've defined a method that cannot be dynamically dispatched, the IBoo trait as a whole is disqualified from being used with dynamic dispatch.

如果你想要某种构造函数,你需要有一些其他的写法.这可以使用普通函数指针,或 IBooFactory trait,就像使用 Java 一样.

If you want some kind of constructor function, you need to have some other way of writing that. This could be using plain function pointers, or an IBooFactory trait, as you might with Java.

这篇关于为什么特征不能构建自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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