簡體   English   中英

編譯器無法推斷 `impl 的 object<trait> ` 在 Rust 中實現了另一個特征</trait>

[英]Compiler cannot infer if an object of `impl <trait>` has impled another trait in Rust

考慮我有一個特征A並且我有很多結構(例如X )實現A 然后我寫了很多小函數(返回這些結構)來抽象我的邏輯。 但是,這些函數的返回類型可能很大而且編寫起來過於復雜(如Chain<Map<'a, (i32, u8), u16, Enumerate<Filter<'a, u8, vec::MoveItems<u8>>>>, SkipWhile<'a, u16, Map<'a, &u16, u16, slice::Items<u16>>>> ),所以我使用impl A代替,因為據我所知, impl <trait>s是仍然發送 static:

trait A {...}
struct X {...}
impl A for X {...}
fn func_to_return_impl_A() -> impl A {...}

現在的問題是,最近我想將我的結構實現到另一個特征B 每當我想將我的小函數返回的值用作: func_to_return_impl_A(...).method_of_trait_B(...)時,編譯器都會抱怨: no implementation for impl A <method of trait B>... 此外,我不能簡單地將返回類型重寫為impl A + B ,因為 trait B也可能包含我自己無法編寫的復雜泛型類型或關聯類型:

impl B for X {...}

fn some_func() {
  func_to_return_impl_A().method_of_trait_B(...) //error: no implementation for impl A <method of trait B> ...
}

我能想到的避免這種情況的唯一方法是制作另一個包裝器來包裝我的所有結構並將其隱含到特征B中,但是隨着 model 變得越來越復雜,這將很難維護。 我應該如何解決這個問題?

好的,我想我已經為我的問題找到了臨時解決方案:附加Wrapper

struct Wrapper<P: A> {
    p: P
}

impl<P: A> A for Wrapper<P> {...}
impl<P: A> B for Wrapper<P> {...}

fn func_to_return_impl_A() -> Wrapper<impl A> {...}

然后我可以使用特征B的方法:

func_to_return_impl_A().method_of_trait_B(...);

暫無
暫無

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

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