rust - 无法分配给 `x`,因为它是借用的

标签 rust

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

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

代码:

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

最佳答案

很难回答您的问题,因为您没有提供足够的信息。特别是,我们需要知道如何 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
}

关于rust - 无法分配给 `x`,因为它是借用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716770/

相关文章:

embedded - 未知的 BlueNRG SPI 响应

rust - 是否可以定义重新分配到 std::vec::Vec 的增量因子?

rust - 清除和重用 Rust PathBuf 的跨平台方法是什么?

rust - 为什么 kcov 计算 Rust 程序的代码覆盖统计数据不正确?

memory-management - Rust 结构体上 getter 方法的借用问题

resources - 有没有好的方法可以将外部资源数据包含到 Rust 源代码中?

loops - 是否有展开或继续循环的快捷方式?

assembly - 如何在(发布的)Rust版本中找到函数的汇编代码?

android - 是否有针对 aarch64-linux-android 的 Rust 版本?

rust - 如何避免 filter_map() 在 Rust 中给出错误 "returns a value referencing data owned by the current function"?