它的任务是使用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/