python - Rust:逐个字符打印出字符串

标签 python rust

它的任务是使用Rust将字符串的文本逐个字符地打印到终端上。

这是我的代码:

use std::time::Duration;
use std::thread::sleep;

fn main() {
    let string = "You are the Semicolon to my Statements.";

    for c in string.chars() {
        print!("{}", c);
        sleep(Duration::from_millis(100));
    }

    println!();
}

运行我的代码时,该字符串仅在循环完成后才打印到终端。

如何按字符打印字符串?

P.S.这是Python 3中的一个工作示例:

import time

string = "You are the Semicolon to my Statements."

for i in string:
    print(i, end='', flush=True)
    time.sleep(0.1)

print()

最佳答案

您需要找到如何在 rust 中使用flush,您的代码应如下所示

use std::time::Duration;
use std::thread::sleep;
use std::io::stdout;
use std::io::Write;

#[allow(unused_must_use)]
fn main() {

   let string = "You are the Semicolon to my Statements.";

   for c in string.chars() {
      print!("{}", c);
      stdout().flush();
      sleep(Duration::from_millis(10));
   };

   println!();

}

关于python - Rust:逐个字符打印出字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59447639/

相关文章:

python - 如何 reshape 文本数据以适合keras中的LSTM模型

vector - 是否可以创建一个引用惰性静态值的向量?

design-patterns - 如何使用特征对象链实现责任链模式?

rust - Rust 是否支持 fork() 跨平台?

rust - 是否可以指定函数参数必须是字符串文字?

python - __enter__ 和 __exit__ 在 python 3 中的类级别

python : split text to list of lines

python - 需要帮助加速此功能

python - 如何向 Sentry 报告当前登录的用户?

rust - 在 Rust 中正确设置生命周期和可变性期望