我不明白為什么 rust 不允許在其他泛型約束中使用泛型。
用普通話很難解釋,但例如這個簡單的代碼不起作用
trait GenericTraitA<T1> {}
trait GenericTraitB<T2> {}
impl<T1, T2: GenericTraitA<T1>> dyn GenericTraitB<T2> {}
它說:
type 引數
T1不受 impl trait、self 型別或謂詞的約束
但我不明白為什么這不受限制,我不明白這段代碼中的歧義。
uj5u.com熱心網友回復:
該編譯器錯誤的意思是,使用該 impl 塊定義,它將無法確定要替換的適當型別 for 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>and Trait<u64>,但是我們怎么知道foo我們應該呼叫哪個版本呢?答案是我們沒有,這就是這個程式無法編譯的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480201.html
上一篇:從元組內容推斷型別
下一篇:多種型別的重用擴展
