如何将盒装特征转换为特征引用? [英] 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;
}
编译器返回以下错误:
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`
如何正确地从Box
借用&T
?
推荐答案
Box
实现 AsRef
trait,它提供了方法as_ref()
,所以你可以以这种方式将其转换为参考:
Box<T>
implements the AsRef<T>
trait, which provides the method as_ref()
, so you can turn it into a reference that way:
let trait_ref: &T = trait_box.as_ref();
通常,deref 强制 意味着你通常不需要明确地写出来.如果您将 Box
类型的值传递给采用 &T
的函数,编译器将为您插入转换.如果您想调用 T
上采用 &self
的方法之一,编译器将为您插入转换.然而,解引用强制不适用于特征,因此这不会发生在特征对象上.
Normally, deref coercions mean that you don't usually need to write this out explicitly. If you pass a value of type Box<T>
to a function that takes &T
, the compiler will insert the conversion for you. If you want to call one of the methods on T
that takes &self
, the compiler will insert the conversion for you. However, deref coercions don't apply to traits, so this won't happen for trait objects.
这篇关于如何将盒装特征转换为特征引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!