Rust:逐个打印字符串字符

3
任务是使用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()

1
flush=True - 这是两个代码片段之间的关键区别。你需要找到如何在 Rust 中执行此操作(刷新标准输出)。 - Sergio Tulentsev
1
尝试使用stdout().flush(); - Ibraheem Ahmed
3个回答

4
你需要找到如何在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!();

}

谢谢,棒极了。特别是 #[allow(unused_must_use)] 这一行,它让编译器忽略了警告。你还包括了所需的库:stdoutWrite,也很不错。 - Alexound
@Alexound 在这种情况下不应该使用 unused_must_use。要么处理 Result,要么调用 stdout().flush().unwrap()must_use 的存在是有充分理由的,而且有更好的方法来处理它,而不是禁用整个函数的 must_use - loganfsmyth

1

我可能会选择更加功能强大和/或习惯的 Rust

fn main() {
    let test = "Test";

    test.chars()
        .for_each(|c| print!("{}", c));
}

我没有尝试过使用 flush(),但如果你真的需要它,你可以添加它并进行测试:

use std::io::stdout;
use std::io::Write; 

fn main() {
    let test = "Test";

    test.chars()
        .for_each(|c|  {
            print!("{}", c);
            stdout().flush(); // this is a Result and should be handled properly
        });
}

0
你需要在循环中添加 stdout().flush();。这是 Rust 中类似于 Python 的 flush=True 的同义词。尝试以下代码。
use std::io::stdout;
use std::io::Write;    
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);
      stdout().flush();
      sleep(Duration::from_millis(100));
   };

   println!();

}

如果没有包含所需的库,这段代码将无法工作。 - Alexound

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接