如何在 Rust 中制作打字机效果
How to do a typewriter effect in rust
所以我正在尝试学习 Rust 的基础知识;我认为这样做的一个好方法可能是将我的旧 python 程序转换为 Rust!我想知道是否有任何方法可以获得打字机效果。因为它在节目中起着关键作用。
这是旧的 python 代码
def scroll(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.075)
现在让我按照
做一些事情time.sleep(.5)
scroll("But there's no sense crying over every mistake.\n")
scroll("You just keep on trying till you run out of cake.\n")
scroll("And the Science gets done.\n")
scroll("And you make a neat gun.\n")
scroll("For the people who are still alive.\n")
time.sleep(1)
基本上用关键字“scroll”替换打印命令我不希望它在 rust 中那么容易;但只要有某种方法可以用来逐个字母地慢慢打印文本,我会很高兴。
我尝试过在线搜索,但是关于这个具体的事情我找不到太多;我已经能够获得为该程序工作所需的所有其他组件;从播放音频到清空终端。
请保持解释简单,因为我是整个编程的新手,但大约一个小时前才开始我的 Rust 之旅。
简单直接的翻译:
use std::io::Write;
fn scroll(s: &str) {
for c in s.chars() {
print!("{c}");
std::io::stdout().flush().expect("Flushing to succeed");
std::thread::sleep(std::time::Duration::from_millis(75));
}
}
fn main() {
scroll("But there's no sense crying over every mistake.\n");
scroll("You just keep on trying till you run out of cake.\n");
scroll("And the Science gets done.\n");
scroll("And you make a neat gun.\n");
scroll("For the people who are still alive.\n");
}
您可以从其他答案中查看它是如何工作的: