簡體   English   中英

嵌套泛型 impl

[英]Nested generic impl

我不明白為什么 rust 不允許在其他泛型約束中使用泛型。

用普通話很難解釋,但例如這個簡單的代碼不起作用

trait GenericTraitA<T1> {}

trait GenericTraitB<T2> {}

impl<T1, T2: GenericTraitA<T1>> dyn GenericTraitB<T2> {}

它說:

類型參數T1不受 impl trait、self 類型或謂詞的約束

但我不明白為什么這不受限制,我不明白這段代碼中的歧義。

該編譯器錯誤的意思是,使用該 impl 塊定義,它將無法確定替換T1的適當類型。 讓我們看一個具體的例子來證明這一點:

pub trait Trait<T> {
    fn foo(&self);
}

struct Bar;

impl Trait<u32> for Bar {
    fn foo(&self) {
        println!("u32 impl");
    }
}

impl Trait<u64> for Bar {
    fn foo(&self) {
        println!("u64 impl");
    }
}

impl<T, U> U
where
    U: Trait<T>,
{
    fn call_foo(&self) {
        self.foo();
    }
}

fn main() {
    let bar = Bar;
    bar.call_foo();
}

嘗試編譯此程序會產生以下錯誤:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:19:6
   |
19 | impl<T, U> U
   |      ^ unconstrained type parameter

存在此錯誤的原因是bar.call_foo()如果我們允許該 impl 塊的格式正確,那么它的行為會模棱兩可。 Bar實現了Trait<u32> <u32> 和Trait<u64> ,但是我們怎么知道我們應該調用哪個版本的foo呢? 答案是我們沒有,這就是這個程序無法編譯的原因。

暫無
暫無

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

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