简体   繁体   English

嵌套泛型 impl

[英]Nested generic impl

I don't understand why rust don't allow to use a generic inside an other generic constraint.我不明白为什么 rust 不允许在其他泛型约束中使用泛型。

It's difficult to explain with normal words but for example this simple code don't work用普通话很难解释,但例如这个简单的代码不起作用

trait GenericTraitA<T1> {}

trait GenericTraitB<T2> {}

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

It says that:它说:

the type parameter T1 is not constrained by the impl trait, self type, or predicates类型参数T1不受 impl trait、self 类型或谓词的约束

But i don't see why this is not constrained, i don't understand the ambiguity inside this code.但我不明白为什么这不受限制,我不明白这段代码中的歧义。

What that compiler error is saying is, with that impl block definition, it would not be able to determine the appropriate type to substitute in for T1 .该编译器错误的意思是,使用该 impl 块定义,它将无法确定替换T1的适当类型。 Let's look at a concrete example to demonstrate this:让我们看一个具体的例子来证明这一点:

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();
}

Trying to compile this program yields the following error:尝试编译此程序会产生以下错误:

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

The reason why this error exists is that bar.call_foo() has ambiguous behavior if we were to allow that impl block to be well-formed.存在此错误的原因是bar.call_foo()如果我们允许该 impl 块的格式正确,那么它的行为会模棱两可。 Bar implements both Trait<u32> and Trait<u64> , but how do we know which version of foo we're supposed to call? Bar实现了Trait<u32> <u32> 和Trait<u64> ,但是我们怎么知道我们应该调用哪个版本的foo呢? The answer is that we don't, which is why this program doesn't compile.答案是我们没有,这就是这个程序无法编译的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM