syntax - `impl TraitX for TraitY` 在 Rust 中意味着什么?

标签 syntax rust traits trait-objects

例如:

trait TraitX { }
trait TraitY { }
impl TraitX for TraitY { }

我认为它的意思是一样的

impl<A: TraitY> TraitX for A { }

但错误消息另有提示:

$ rustc --version
rustc 0.12.0-nightly (a70a0374e 2014-10-01 21:27:19 +0000)
$ rustc test.rs
test.rs:3:17: 3:23 error: explicit lifetime bound required
test.rs:3 impl TraitX for TraitY { }
                          ^~~~~~

impl TraitX for TraitY(或具有显式生命周期的它的某些变体)在 Rust 中有什么意义吗?如果是这样,它的使用示例是什么?

最佳答案

impl TraitX for TraitY正在使用 TraitY作为a dynamically sized type (DST) .如果我们添加所需的生命周期限制(参见例如 this 了解有关生命周期限制必要性的更多信息),编译器将以这种方式提示:

trait TraitX { }
trait TraitY { }
impl<'a> TraitX for TraitY+'a { }

fn main() {}

<anon>:3:1: 3:34 error: the trait `core::kinds::Sized` is not implemented for the type `TraitY+'a`
<anon>:3 impl<'a> TraitX for TraitY+'a { }
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:3:1: 3:34 note: the trait `core::kinds::Sized` must be implemented because it is required by `TraitX`
<anon>:3 impl<'a> TraitX for TraitY+'a { }
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

playpen

错误是说 TraitY+'a没有大小,也就是说,它在编译时没有已知的大小(例如 u8 的大小为 1,Vec<T> 是 3 个指针的大小)。

语法正在执行 TraitX对于 TraitY trait 对象(这些在引用的 "object types" section 中涵盖),允许在值实现 TraitX 的地方处理它(在指针后面)是期待。工作用法涉及一些额外的 Sized?注释,这些表示它们所附加的任何东西都是可选的 ( ? ) 大小(默认是假定大小的东西)。

#![allow(dead_code)]

// indicate that it's OK to implement this trait for DSTs
trait TraitX for Sized? { } 
trait TraitY { }
trait TraitZ { }

impl<'a> TraitX for TraitY+'a { }

// the Sized? is to allow DSTs to be passed to this.
fn example<Sized? T: TraitX>(_: &T) {}

fn call_it(x: &TraitY, _y: &TraitZ) {
    example::<TraitY>(x); // only possible if `TraitY` impls `TraitX`.

    // error:
    // example::<TraitZ>(_y);  // `TraitZ` doesn't impl `TraitX`.
}

fn main() {}

playpen

显式 ::<TraitY>现在使用未确定大小的类型调用函数时需要类型提示,但这是一个错误 #17178 .目前,还有 quite a few bugs with DST所以在实践中实际使用起来并不容易,但这会有所改善。

DST 的主要动机是使处理特征对象与其他指针类型更加一致,例如我们目前只支持&TraitBox<Trait>特征对象,但 DST 旨在允许其他指针类型,如 Rc<Trait> , Arc<Trait> . DST 还允许将它们视为真正的指针,例如如果obj: Box<Trait>然后 &*obj现在只有 DST 才有可能,以前它是非法的,因为特征对象是胖指针,而不是普通指针。

关于syntax - `impl TraitX for TraitY` 在 Rust 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201171/

相关文章:

c++ - 在 C++ 中存储字符串时,char* 和 char 有什么区别?

python - "None not in"与 "not None in"

rust - 要求类型参数是结构

mysql,程序中的语法问题

t-sql - DB2相当于SQL的GO?

rust - 将 "*mut *mut f32"转换为 "&[&[f32]]"

syntax - 如何以干净的方式混合 bool 比较和 'if let' 语句?

java - Groovy traits 是否支持与 Java 联合编译?

generics - 如何将值映射到 Rust 中的类型?

generics - 如何为类型引用的操作指定通用特征?