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

为何已克隆/复制的值仍触发Rust引用错误E0515?

解决Rust E0515引用错误:返回值引用本地变量问题

错误信息

error[E0515]: cannot return value referencing local variable `s1`
   --> src/regexp/mod.rs:538:9
    |
528 |             match s1.step() {
    |                   --------- `s1` is borrowed here
...
538 |         steps
    |         ^^^^^ returns a value referencing data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `regexp` due to previous error

问题背景

已经为CharsStep实现了Clone和Copy trait,无论是直接推入克隆对象还是先赋值副本再推入,都依然触发上述引用错误。明明已经做了克隆操作,却还是被判定为返回了对本地值的引用,完全搞不懂哪里出了问题。

相关代码

pub trait Walker {}
    
// used to hold the state at each step in the search walk, and later to build the final result if successful
#[derive(Clone, Copy)]
struct CharsStep<'a> {
    node: &'a CharsNode,
    string: &'a str,
    matched: &'a str,
}

impl<'a> Walker for CharsStep<'a> {}

impl<'a> CharsStep<'a> {
    fn walk(node: &'a CharsNode, string: &'a str) -> Vec<Box<dyn Walker + 'a>> {
        let mut steps = Vec::<Box<dyn Walker>>::new();
        let mut step = CharsStep {
            node,
            string,
            matched: "",
        };
        if node.limit_desc.0 == 0 {
            steps.push(Box::new(step.clone()));
        }

        for i in 1..node.limit_desc.1 {
            let s1 = step;
            match s1.step() {
                Some(s) => {
                    if i >= node.limit_desc.0 {
                        steps.push(Box::new(s.clone()));
                    }
                    step = s.clone();
                }
                None => {
                    break;
                }
            }
        }
        steps
    }
    
    fn step(&self) -> Option<CharsStep> {
        let len = self.node.string.len();
        if self.string[0..len] == self.node.string {
            Some(CharsStep {
                node: self.node,
                string: &self.string[len..],
                matched: &self.string[..len],
            })
        } else {
            None
        }
    }
}

问题原因与解决方案

问题出在step方法的生命周期推断上:

  • 你没有为step方法的返回值显式指定生命周期,Rust会默认推断为fn step(&'b self) -> Option<CharsStep<'b>>,这里的'b是调用step时self的生命周期(也就是本地变量s1的生命周期,仅存在于当前循环块内)。
  • 但你需要的是返回CharsStep<'a>(和结构体自身的生命周期一致,也就是函数参数传入的'a生命周期),因为CharsStep里的所有引用都来自'a生命周期的输入,而非本地变量s1。

修复步骤

  1. 修改step方法的签名,显式指定返回值的生命周期为'a:
fn step(&self) -> Option<CharsStep<'a>> {
  1. 同时,将walk函数内的steps变量显式标注生命周期,避免推断歧义:
let mut steps = Vec::<Box<dyn Walker + 'a>>::new();

这样修改后,编译器就能正确识别返回的CharsStep持有是'a生命周期的引用,不会再和本地变量s1的短生命周期绑定,错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:47