简体   繁体   English

"如何将盒装特征转换为特征参考?"

[英]How to convert a boxed trait into a trait reference?

I have the following code that tries to take a reference to a trait object from a boxed trait:我有以下代码尝试从盒装特征中获取对特征对象的引用:

trait T {}

struct S {}

impl T for S {}

fn main() {
    let struct_box: Box<S> = Box::new(S {});
    let struct_ref: &S = &struct_box;

    let trait_box: Box<T> = Box::new(S {});
    let trait_ref: &T = &trait_box;
}

The compiler returns the following error:编译器返回以下错误:

error[E0277]: the trait bound `std::boxed::Box<T>: T` is not satisfied
  --> src/main.rs:12:25
   |
12 |     let trait_ref: &T = &trait_box;
   |                         ^^^^^^^^^^ the trait `T` is not implemented for `std::boxed::Box<T>`
   |
   = note: required for the cast to the object type `T`

How do I properly borrow &T from Box<T> ?如何从Box<T>正确借用&T

Box<T> implements the AsRef<T> trait , which provides the method as_ref() , so you can turn it into a reference that way: Box<T>实现 AsRef<T>特征,它提供了as_ref()方法,因此您可以通过这种方式将其转换为引用:

let trait_ref: &T = trait_box.as_ref();

Normally, deref coercions mean that you don't usually need to write this out explicitly.通常, deref 强制意味着您通常不需要明确地写出来。 If you pass a value of type Box<T> to a function that takes &T , the compiler will insert the conversion for you.如果您将Box<T>类型的值传递给采用&T的函数,编译器将为您插入转换。 If you want to call one of the methods on T that takes &self , the compiler will insert the conversion for you.如果您想调用T上采用&self的方法之一,编译器将为您插入转换。 However , deref coercion doesn't apply to a cast to a trait object type (the compiler will choose an unsizing coercion instead, which is what happens in your example).但是, deref coercion 不适用于转换为 trait 对象类型(编译器将选择 unsizing coercion 代替,这就是您的示例中发生的情况)。

Borrow the contents of the Box , rather than the Box itself:借用Box的内容,而不是Box本身:

let trait_ref: &T = &*trait_box;

The reason the line involving &S works is because the only way for Rust to get from Box<S> to &S is via "deref coercion";涉及&S的行起作用的原因是,Rust 从Box<S>&S的唯一方法是通过“deref coercion”; that is, it repeatedly dereferences the value until either the types match, or it can't dereference any further.也就是说,它反复取消引用该值,直到类型匹配,或者它不能进一步取消引用。

Coercing to a trait object, on the other hand, isn't done using dereferencing at all;另一方面,强制转换为 trait 对象根本不是使用解引用完成的。 it involves constructing a new pointer directly from the given one.它涉及直接从给定的指针构造一个新指针。 If it can't do that, it fails.如果它不能做到这一点,它就会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM