Self::Outp-6ren">
gpt4 book ai didi

rust - Rust 出现 "cannot extract an associated type from a higher-ranked trait bound in this context"错误

转载 作者:行者123 更新时间:2023-12-03 11:45:55 26 4
gpt4 key购买 nike

当我运行使用更高级别特征边界的代码时:

pub trait MyTrait<'a> {
type Output: 'a;
fn gimme_value(&self) -> Self::Output;
}

pub fn meow<T: for<'a> MyTrait<'a> + 'static>(val: &T) -> T::Output {
val.gimme_value()
}

我看到这个错误:
error[E0212]: cannot extract an associated type from a higher-ranked trait bound in this context

我怎样才能使我的功能 meow返回此关联类型,同时仍允许 T成为更高级别的特质绑定(bind)?

最佳答案

只需向 meow 添加一个新的泛型即可函数——我们称之为R .为 T 添加特征限制时, 定义 T::Output等于 R .然后,让函数返回 R而不是 T::Output :

pub trait MyTrait<'a> {
type Output: 'a;
fn gimme_value(&self) -> Self::Output;
}

pub fn meow<R, T: for<'a> MyTrait<'a, Output=R> + 'static>(val: &T) -> R {
val.gimme_value()
}

关于rust - Rust 出现 "cannot extract an associated type from a higher-ranked trait bound in this context"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60678951/

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