尝试将更多元素推送到向量时出现以下错误。如何克服这个错误
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/