gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:57:06 24 4
gpt4 key购买 nike

例如:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com