当我运行使用更高级别特征边界的代码时:
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/