【发布时间】:2021-02-10 22:27:11
【问题描述】:
我正在通过一些编程练习自学 Rust。在这里,我有一个Vec<String> 我从一个文件中读出,我试图将每一行中的字母放在HashSet 中,然后取所有行的交集。
当我这样做时,我收到一个错误,说我的循环变量的寿命不够长。
我有一个直觉,哪里出了问题——我有一个变量l,它的生命周期是循环的一次迭代,另一个变量候选者的生命周期是整个循环,第二个变量是从第一个变量借来的。但是我该如何解决呢?
let mut candidates = HashSet::<&u8>::new();
let mut sum = 0;
for l in lines { // lines is Vec<String>
if candidates.len()==0 {
candidates = HashSet::<&u8>::from_iter(l.as_bytes());
println!("candidates = {:?}", candidates);
} else if l.len() == 0 { // error message "borrow later used here"
// end of group
sum = sum + candidates.len();
candidates = HashSet::<&u8>::new();
} else {
let h2 = HashSet::<&u8>::from_iter(l.as_bytes()); // error message "borrowed value does not live long enough"
candidates = candidates.intersection(&h2).copied().collect();
println!("candidates = {:?}", candidates);
}
println!("{}", l);
}
我尝试复制l
let mut l2:String = "".to_string();
for l in lines {
if candidates.len()==0 {
l2 = l.to_string();
candidates = HashSet::<&u8>::from_iter(l2.as_bytes());
但我得到一个不同的错误说error[E0506]: cannot assign to l2 because it is borrowed。
【问题讨论】:
-
你能像
for l in &lines {那样借用吗?
标签: loops rust set lifetime borrow-checker