无法分配给x,因为它是借来的

时间:2019-11-05 17:44:13

标签: rust

尝试将更多元素推到向量时出现以下错误。如何克服这个错误

CourseRegModel

代码:

error[E0506]: cannot assign to `x` because it is borrowed

x = format!(r"\*START TIME*{:?}\S*\s+(?P<Value>[a-zA-Z0-9_\-\.]+)", ts);
   |         ^^ assignment to borrowed `x` occurs here
76 |         core_regex_dict.push(&x);
   |         ---------------      --- borrow of `x` occurs here
   |         |
   |         borrow later used here

2 个答案:

答案 0 :(得分:-1)

很难回答您的问题,因为您没有给我们足够的信息。特别是,我们需要知道core_regex_dict的定义。我假设core_regex_dict的类型为Vec<&str>。您需要将其更改为Vec<String>

let core_regex_dict = Vec::new(); // No need to specify the item type, it will be inferred.
// No need to declare `x` before the loop unless you need to use the 
// last value afterward...
for ts in test_list {
    let x = format!(r"\*START TIME*{:?}\S*\s+(?P<Value>[a-zA-Z0-9_\-\.]+)", ts);
    core_regex_dict.push (x);  // No `&` -> we push the String itself instead of a reference
}

答案 1 :(得分:-4)

找到了一种解决方案,其中涉及泄漏https://stackoverflow.com/a/30527289/12323498String的内存

但是,有没有更好的方法可以做到这一点而不泄漏内存呢?

fn string_to_static_str(s: String) -> &'static str {
    Box::leak(s.into_boxed_str())
}

现在代码看起来像这样

let mut s = String::new();
    for ts in test_list {
        s = format!(r"\*START TIME*{:?}\S*\s+(?P<Value>[a-zA-Z0-9_\-\.]+)", ts);
        let s: &'static str = string_to_static_str(s);
        core_regex_dict.push(s);  
    }