记录一条在 Rust 中发生变化的消息?

问题描述 投票:0回答:1

G'day,我正在尝试记录一条可以随变量更改的消息。 我的意思是:

  • 使用变量 a、b 打印消息
  • 删除消息
  • 使用 a、b 的不同值再次打印 现在,它不完全是一个进度条,所以我不能使用像 inidcatif 这样的东西。

我尝试过使用这个:

    let message = format!(
        "\x1B[2K\rA: {}, B: {}",
        a, b
    );

    print!("{}", message);
    std::io::stdout().flush().unwrap();

但这只是多次打印该行并且不喜欢,请更改该行

logging rust progress-bar
1个回答
0
投票

您的终端实际上支持 ANSI 转义码吗?因为它对我来说效果很好:

use std::io::Write;

fn main() {
    for (a, b) in std::iter::zip(0.., &["A", "B", "C", "D"]) {
        let message = format!("\x1B[2K\rA: {}, B: {}", a, b);

        print!("{}", message);
        std::io::stdout().flush().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1))
    }
}

确实显示线路随时间变化。

顺便说一句,

format!
是不必要的,您可以直接格式化
print!
中的所有内容

use std::io::Write;

fn main() {
    for (a, b) in std::iter::zip(0.., &["A", "B", "C", "D"]) {
        print!("\x1B[2K\rA: {a}, B: {b}");
        std::io::stdout().flush().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.