在循环终止后如何打印频率HashSet
?问题似乎在于无法保证循环终止。
use std::collections::HashSet;
use std::fs;
fn main() {
let f = fs::read_to_string("input.txt").expect("Unable to open file");
let mut total = 0;
let mut frequencies = HashSet::new();
frequencies.insert(0);
loop {
for line in f.lines() {
let line_trimmed = line.trim();
let something = line_trimmed.parse::<i32>().unwrap();
total += something;
// println!("{:?}",total);
if frequencies.contains(&total) {
println!("duplicated found {:?}", total);
return;
}
frequencies.insert(total);
}
}
println!("duplicated found {:?}", frequencies);
}
答案 0 :(得分:3)
println!("duplicated found {:?}", frequencies);
无法访问,因为在调用return
时,您正在返回main
函数。
将循环更改为while,并设置一个变量以退出while循环。
let mut duplicated_found = false;
while !duplicated_found {
for line in f.lines() {
let line_trimmed = line.trim();
let something = line_trimmed.parse::<i32>().unwrap();
total += something;
// println!("{:?}",total);
if frequencies.contains(&total) {
println!("duplicated found {:?}", total);
duplicated_found = true;
break; // This breaks out of the for loop
}
frequencies.insert(total);
}
}
println!("duplicated found {:?}", frequencies);
或者您可以使用标签指定要突破的循环:
'outer: loop {
for line in f.lines() {
let line_trimmed = line.trim();
let something = line_trimmed.parse::<i32>().unwrap();
total += something;
// println!("{:?}",total);
if frequencies.contains(&total) {
println!("duplicated found {:?}", total);
break 'outer; // This breaks out of the outer loop
}
frequencies.insert(total);
}
}
println!("duplicated found {:?}", frequencies);