gpt4 book ai didi

loops - E0597试图在向量上循环

转载 作者:行者123 更新时间:2023-12-03 11:32:25 25 4
gpt4 key购买 nike

我通过做一些编程练习来教自己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

最佳答案

as_bytes将您的l字符串转换为 byte slice 。切片是对连续元素序列的引用。编译器指出,在for循环的末尾,该引用无效。
一种解决方案是使用&lines遍历String引用:

    let mut candidates = HashSet::<&u8>::new();
let mut sum = 0;
for l in &lines { // <= HERE iter over String references which lives outside the for loop
if candidates.len()==0 {
candidates = HashSet::<&u8>::from_iter(l.as_bytes());
println!("candidates = {:?}", candidates);
} else if l.len() == 0 {
// end of group
sum = sum + candidates.len();
candidates = HashSet::<&u8>::new();
} else {
let h2 = HashSet::<&u8>::from_iter(l.as_bytes());
candidates = candidates.intersection(&h2).copied().collect();
println!("candidates = {:?}", candidates);
}
println!("{}", l);
}
第二种解决方案是复制l String。
    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.clone().into_bytes());
println!("candidates = {:?}", candidates);
} else if l.len() == 0 {
// end of group
sum = sum + candidates.len();
candidates = HashSet::<u8>::new();
} else {
let h2 = HashSet::<u8>::from_iter(l.clone().into_bytes());
candidates = candidates.intersection(&h2).copied().collect();
println!("candidates = {:?}", candidates);
}
println!("{}", l);
}

关于loops - E0597试图在向量上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66146029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com