You need to enable JavaScript to run this app. Rust创建遍历&mut self的函数时生命周期标注问题如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Rust创建遍历&mut self的函数时生命周期标注问题如何解决?

问题原因

你的代码核心问题是返回值的生命周期参数'out没有和输入的Reader引用的生命周期做绑定,Rust无法确认返回的切片和BytesStart的有效存活范围,自然无法通过生命周期校验。
你调用的read_namespaced_event方法返回的事件、命名空间切片,生命周期都是和你传入的缓冲区buf的生命周期绑定的,而buf是Reader结构体的成员,所以返回值的生命周期必须和你传入的&mut Reader的生命周期保持一致。

修正后的代码

删掉无意义的游离生命周期参数,将返回值生命周期和输入参数绑定即可:

// 若Reader结构体本身带有生命周期参数,将对应生命周期和'a关联即可
fn next<'a>(reader_: &'a mut Reader<B>) -> Option<(&'a [u8], BytesStart<'a>)> {
    let test = loop {
        let Reader { reader, ns, buf } = reader_;
        let e = reader
            .read_namespaced_event(buf, ns)
            .map(|(ns, e)| (ns.unwrap_or(&[]), e));
        match e {
            Ok((ns, Event::Start(start))) => {
                break Some((ns, start));
            }
            _ => {}
        }
    };
    test
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:57:03