gpt4 book ai didi

rust - 打印!循环外是一个无法访问的语句,如何以 "reachable"方式使用 println

转载 作者:行者123 更新时间:2023-11-29 08:34:27 24 4
gpt4 key购买 nike

如何在循环终止后打印频率 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);
}

最佳答案

println!("duplicated found {:?}", frequencys); 无法访问,因为当您调用 return 时,您正在返回 主要功能。

将循环改为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);

关于rust - 打印!循环外是一个无法访问的语句,如何以 "reachable"方式使用 println,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54817335/

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