You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用约束性高阶Trait边界时出现类型不匹配问题求助

Rust泛化高阶Trait边界代码时的类型不匹配问题

这是此前“显式声明生命周期时出现dropped here while still borrowed错误”问题的跟进,可独立查看。在@jthulhu的帮助下,我借助**高阶Trait边界(HRTB)**解决了之前的错误,现在想要进一步泛化代码。

我定义了如下Trait:

trait ToImplement {
    type Arg<'arg>;
    fn do_something<F>(&self, f: F)
    where
        F: for<'b> FnOnce(Self::Arg<'b>) -> ();
}

为String实现该Trait后直接使用是正常的,测试代码如下:

impl ToImplement for String {
    type Arg<'arg> = &'arg str;
    fn do_something<F, T>(&self, f: F) -> T
    where
        F: for<'b> FnOnce(Self::Arg<'b>) -> T,
    {
        f(&self)
    }
}

#[test]
fn works() {
    let hello = String::from("Hello");
    let r = hello.do_something(|s| format!("{s} world!"));
    assert_eq!(r,"Hello world!")
}

但当我编写一个不依赖具体实现类型、仅对Arg类型加约束的go函数时:

fn go<D, I>(implementor: I)
where
    D: Display,
    for<'a> I: ToImplement<Arg<'a> = D>,
{
    implementor.do_something(|a| println!("{a}"));
}

调用go(hello)时出现如下编译错误:

error[E0308]: mismatched types
   |
36 |         go(hello);
   |         ^^^^^^^^^ one type is more general than the other
   |
   = note: expected reference `&'a str`
              found reference `&str`
note: the lifetime requirement is introduced here
   |
13 |     for<'a> I: ToImplement<Arg<'a> = D>,
   |   

我认为第13行的生命周期'a声明方式有误,但不知道该如何修正。我查阅了Rustonomicon的所有权章节以及Borrow splitting相关内容,也参考了Take的实现,但未找到解决方法。


内容的提问来源于stack exchange,提问作者Xavier Detant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:30:12