[英]How to convert a boxed trait into a trait reference?
我有以下代碼嘗試從盒裝特征中獲取對特征對象的引用:
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>
正確借用&T
?
Box<T>
實現 了AsRef<T>
特征,它提供了as_ref()
方法,因此您可以通過這種方式將其轉換為引用:
let trait_ref: &T = trait_box.as_ref();
通常, deref 強制意味着您通常不需要明確地寫出來。 如果您將Box<T>
類型的值傳遞給采用&T
的函數,編譯器將為您插入轉換。 如果您想調用T
上采用&self
的方法之一,編譯器將為您插入轉換。 但是, deref coercion 不適用於轉換為 trait 對象類型(編譯器將選擇 unsizing coercion 代替,這就是您的示例中發生的情況)。
借用Box
的內容,而不是Box
本身:
let trait_ref: &T = &*trait_box;
涉及&S
的行起作用的原因是,Rust 從Box<S>
到&S
的唯一方法是通過“deref coercion”; 也就是說,它反復取消引用該值,直到類型匹配,或者它不能進一步取消引用。
另一方面,強制轉換為 trait 對象根本不是使用解引用完成的。 它涉及直接從給定的指針構造一個新指針。 如果它不能做到這一點,它就會失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.