簡體   English   中英

trait upcast coercion workaround 是如何工作的(獲取 supertrait 實例的 trait 方法)?

[英]How does the trait upcast coercion workaround work (trait method for getting an instance of the supertrait)?

看起來 Rust 不允許在需要引用超特征實例的地方使用對特征實例的引用:

trait Animal{}
trait Dog: Animal{}

fn convert(dog: &Dog) -> &Animal {
    dog // Error: trait upcasting coercion is experimental, see issue #65991 ...
}

但是有一種解決方法,經常在Rust-Analyzer 代碼庫中使用。 解決方法如何工作?

這是解決方法,它使我們能夠編寫rustc將接受的convert

trait Animal{}
trait Dog: Animal{
    fn upcast(&self) -> &Animal; // added line
}
fn convert(dog: &Dog) -> &Animal {
    dog.upcast() // changed line
}

這是upcast的一個實現:

struct Foo {}
impl Animal for Foo {}
impl Dog for Foo {
    fn upcast(&self) -> &Animal {
        self
    }
}

比較upcast和原始convert :它們具有相同的簽名和相同的實現(模重命名)。 因此,對於函數不允許的方法,似乎允許某些東西。 發生了什么?

upcast()中的&self不是&dyn Dog ,而是具體的&Foo 這是對dyn Trait方法的通常調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM