gpt4 book ai didi

rust - 涉及关联类型的不满足特征界限

转载 作者:行者123 更新时间:2023-11-29 07:58:44 24 4
gpt4 key购买 nike

代码

pub trait Q<S> {
fn f();
}

pub trait A {
type I;
type F: Q<Self::I>;
}

// this works (1)
//
// pub struct S<T>
// where
// T: A
// {

// unsatisfied trait bound (2)
pub struct S<T>
where
T: A<I = bool>,
{

t: T,
}

编译失败:

error[E0277]: the trait bound `<T as A>::F: Q<bool>` is not satisfied
--> src/main.rs:18:1
|
18 | / pub struct S<T>
19 | | where
20 | | T: A<I = bool>,
21 | | {
22 | | t: T,
23 | | }
| |_^ the trait `Q<bool>` is not implemented for `<T as A>::F`
|
= help: consider adding a `where <T as A>::F: Q<bool>` bound
= note: required by `A`

有趣的是,如果您使用注释掉的行 (1) 而不是 (2),它会起作用。如果您将关联类型转为 I,它也会起作用转换为通用类型(写入 trait A<I>A<bool> )。

impl<T> S<T>
where T: A
{
fn g() {
T::F::f()
}
}

第 (1) 行或通用类型成功 I , 所以 T::F : Q<bool>在这些情况下确实是假定的。

为什么第 (1) 行或泛型自动假定特征绑定(bind),而不是第 (2) 行?

我们可以在不附加 where T::F: Q<bool> 的情况下修复上面的代码吗?每次我们使用T: A<I=bool>

最佳答案

从 Rust 1.18 开始,编译器要求您编写这些边界以使类型格式良好。基本上,为了绑定(bind) T: A<I = bool>持有,需要绑定(bind)T::F: Q<bool>也成立。例如,如果某种类型试图实现 A像这样:

struct Y;
struct Z;

impl A for Y {
type I = bool;
type F = Z; // Z does not implement Q<bool>
}

然后 Y不会合式,因为绑定(bind) T::F: Q<bool>不成立(事实上,编译器在 impl 上给出错误)。但令人沮丧的是,目前,绑定(bind) T::F: Q<bool>必须在绑定(bind) T: A<I = bool> 时明确给出出现。在某种程度上,它让编译器放心,嘿,T::I = bool还有!

Why is the trait bound automatically assumed with line (1) or generic types, but not with line (2)?

对于第 (1) 行,界限将是 T::F: Q<T::I> ,这正是 A 的要求(用 T 代替 Self )。事实上,我们也可以像这样等价地写出边界:

pub trait A
where
Self::F: Q<Self::I>,
{
type I;
type F;
}

在第 (2) 行中,边界 T::F: Q<bool>可能看起来只是替换 T::I 的问题与 bool ,但这种差异对编译器很重要; T::I是关联类型,而 bool是具体类型。


Rust 开发人员正在考虑改进编译器,这样就不必在所有地方重复这样的边界 by having the compiler infer those bounds .

关于rust - 涉及关联类型的不满足特征界限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com