gpt4 book ai didi

rust - "overflow evaluating the requirement"尝试延迟关联类型时

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

在 Rust 中,我试图延迟类型以测试解耦的高级逻辑。理想情况下,我想将最小关系规则表达为关联类型的类型约束。在这个简化的示例中,错误类型之间唯一的关键关系是它们的值可以从低级转换为高级。

虽然这些关系看起来应该终止,但编译器会因“溢出评估需求”而出错。我无法确定我的类型函数是否有缺陷,或者我是否遇到了 Rust 中已知或未知的限制。示例:

pub trait CapabilityA {
type Error;
fn perform_a(&self) -> Result<String, Self::Error>;
}

pub trait CapabilityB {
type Error;
fn perform_b(&self, a: &str) -> Result<(), Self::Error>;
}

pub trait Application {
type Error;
fn go(&self) -> Result<(), Self::Error>;
}

impl<T> Application for T
where
T: CapabilityA + CapabilityB,
<T as Application>::Error: From<<T as CapabilityA>::Error> + From<<T as CapabilityB>::Error>,
{
fn go(&self) -> Result<(), Self::Error> {
let a = self.perform_a()?;
let b = self.perform_b(&a)?;
Ok(b)
}
}

编译器响应:

error[E0275]: overflow evaluating the requirement `<Self as Application>::Error`
--> src/lib.rs:11:1
|
11 | / pub trait Application {
12 | | type Error;
13 | | fn go(&self) -> Result<(), Self::Error>;
14 | | }
| |_^
|
= note: required because of the requirements on the impl of `Application` for `Self`

最佳答案

一个更简单的例子 reproducing the same error是:

pub trait Foo {}

pub trait Application {
type Error;
}

impl<T> Application for T where <T as Application>::Error: Foo {}

您对 Application 的定义是递归的。想知道什么T实现 Application , 你需要评估 <T as Application> ,这需要编译器知道什么 T实现 Application , 等等。

在执行Application ,你必须选择一个具体的Error ,例如 here with String :

impl<T> Application for T
where
T: CapabilityA + CapabilityB,
String: From<<T as CapabilityA>::Error>,
String: From<<T as CapabilityB>::Error>,
{
type Error = String;

fn go(&self) -> Result<(), Self::Error> {
let a = self.perform_a()?;
let b = self.perform_b(&a)?;
Ok(b)
}
}

关于rust - "overflow evaluating the requirement"尝试延迟关联类型时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55857823/

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