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

标签 rust

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

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/

相关文章:

pointers - 指向 Result<Vec<f64>, _> 中向量第一个元素的指针已损坏

lambda - 传递和评估防 rust 封闭

iterator - 使用 HashMap 实现类 SQL RIGHT OUTER JOIN 的迭代器适配器

rust - 将本地值插入静态 mut 的安全方法

recursion - 在 Rust 中返回一个递归闭包

rust - 打印!借用或拥有变量?

rust - 为什么这个 Trait 无效?以及使用什么签名来代替?

rust - "aliased ptr with a non-none lp"在 Rust 中意味着什么

floating-point - 将 float 转换为包含所有数字的字符串

pattern-matching - 为什么这个结构在模式匹配后没有 move ?