【问题标题】:Programming in Rust , how to fix error[E0515] "cannot return value referencing local variable"?Rust 编程,如何修复错误[E0515]“无法返回引用局部变量的值”?
【发布时间】:2021-01-01 10:23:01
【问题描述】:

请帮我编译下面附上的代码。编译器说,根据我注释掉的行,遵循 2 种模式。

程序读取一个 &str ,它是一个简单的“svg 路径命令”,类似于代码然后解析它。为简单起见,已对粘贴的代码进行了简化。它使用正则表达式将输入字符串拆分为行,然后研究主 for 循环中的每一行。每个循环将解析结果推送到一个向量上。最后函数返回向量。

基本上编译器说返回向量是不允许的,因为它引用了局部变量。虽然我没有任何解决方法。

error[E0597]: `cmd` does not live long enough
  --> src/main.rs:24:25
   |
24 |    codeV =  re.captures(cmd.as_str());
   |    -----                ^^^ borrowed value does not live long enough
   |    |
   |    borrow might be used here, when `codeV` is dropped and runs the destructor for type `Option<regex::Captures<'_>>`
...
30 |    }
   |    - `cmd` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are defined

error[E0515]: cannot return value referencing local variable `cmd`
  --> src/main.rs:31:1
   |
24 |    codeV =  re.captures(cmd.as_str());
   |                         --- `cmd` is borrowed here
...
31 | V //Error
   | ^ returns a value referencing data owned by the current function

Playground

use regex::Regex;
pub fn parse(path:&str) {//->Vec<Option<regex::Captures<>>>  //Error
    let reg_n=Regex::new(r"\n").unwrap();
    let path=reg_n.replace_all("\n"," ");
    let reg_cmd=Regex::new(r"(?P<cmd>[mlhv])").unwrap();
    let path=reg_cmd.replace_all(&path,"\n${cmd}");
    let cmdV=reg_n.split(&path);
   
    //let cmdV:Vec<&str> = reg.split(path).map(|x|x).collect();    

    let mut V:Vec<Option<regex::Captures<>>>=vec![];
    let mut codeV:Option<regex::Captures<>>=None;
    let mut count=0;
    for cmd_f in cmdV{//This loop block has been simplified.
        count+=1;
        if count==1{continue;}
        let mut cmd="".to_string();
   
        cmd=cmd_f.to_string();
        cmd=cmd.replace(" ","");
        let re = Regex::new(r"\{(?P<code>[^\{^\}]{0,})\}").unwrap();
        codeV =  re.captures(cmd.as_str());
        //cmd= re.replace_all(cmd.as_str(),"").to_string();
        let cmd_0=cmd.chars().nth(0).unwrap();
        //cmd.remove(0);
        //V.push(codeV);   //Compile error
        V.push(None); //OK
    }
    //V
}

fn main() {
    parse("m {abcd} l {efgh}");
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    虽然我没有任何解决方法。

    正则表达式的捕获指的是它们匹配的字符串以提高效率。这意味着他们不能超过该字符串,因为匹配组本质上只是该字符串的偏移量。

    由于您匹配的字符串是在循环体中创建的,这意味着捕获无法逃脱循环体。

    除了不在循环体(甚至函数)中创建字符串之外,解决方案/解决方法是将捕获组转换为拥有的数据并将其存储:而不是尝试返回捕获向量,而是从捕获中提取您真正想要的数据,将其转换为拥有的String(或其元组,或其他),并将其推送到您的向量上。

    例如https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0107333e30f831a418d75b280e9e2f31

    【讨论】:

      【解决方案2】:

      如果您不确定该值是否已借用,您可以使用cmd.clone().as_str()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 2016-01-19
        • 2016-06-13
        • 1970-01-01
        相关资源
        最近更新 更多