要在 Rust 中实现控制台刷新而不换行,以实现类似 "loading" 状态的效果,你可以使用 \r(回车符)来覆盖上一行的内容。
use std::io::{self, Write};
use std::thread;
use std::time::Duration;
fn main() {
let loading_chars = vec!['-', '\\', '|', '/'];
let mut index = 0;
loop {
print!("\rLoading {} ", loading_chars[index]);
io::stdout().flush().unwrap();
index = (index + 1) % loading_chars.len();
thread::sleep(Duration::from_millis(250));
}
}
在这个示例中,我们使用一个字符向量 loading_chars 来表示不同的加载状态。然后,我们在一个循环中不断打印当前加载状态,并使用 \r 来回车到行首,实现不换行刷新的效果。通过不断更新 index 变量来循环显示不同的加载状态字符。
运行这段代码,你会看到控制台中打印出一个不断刷新的 "loading" 状态,每隔一段时间更新一次加载状态字符。你可以根据需要调整加载状态字符和刷新频率。
实现进度刷线显示功能:
use std::thread;
use std::time::Duration;
use std::io::{self, Write};
fn main() {
for i in 0..=10 {
print!("\rProgress: {}%", i * 10);
io::stdout().flush().unwrap();
// 等待一段时间,模拟耗时操作
thread::sleep(Duration::from_secs(1));
}
println!("\nDone!");
}
实现效果:




![Cocos2dx-lua ScrollView[三]高级篇](https://img-blog.csdnimg.cn/direct/6b3c230be38d46f688e1c12f7c07b39a.gif)
![[flink] flink macm1pro 快速使用从零到一](https://img-blog.csdnimg.cn/img_convert/4ad8d3bd3368a641131a7ae571e1ad34.png)














