-1

So I'm attempting to learn the basics of rust; and I thought a good way of doing that might be to convert an old python program of mine to rust! I was wondering if there was any way to get a typewriter effect. As it plays a key role in the program.

Here's the old python code

def scroll(str):


  for letter in str:
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(0.075)

now that let me do something along the lines of

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)

Essentially replace the print command with the keyword "scroll" I don't expect it to be that easy in rust; but as long as there's some method I can use to slowly print text letter by letter I'll be happy.

I've attempted searching online but there's not much that I can find in regards to this specific thing; I've been able to get every other component I need working for the program; from playing audio to clearing the terminal.

Please keep the explanations simple as I'm new to programming as a whole, but only started my Rust journey about an hour ago.

python_user
  • 5,375
  • 2
  • 13
  • 32
Xanthus
  • 55
  • 1
  • 9
  • 2
    `I've attempted searching online but there's not much that I can find in regards to this specific thing`, I think you should check on simple things like: `how to print a character?`, `how to sleep?`, `how to loop?`, otherwise it should be pretty straight forward. – Netwave May 17 '22 at 07:31

1 Answers1

1

A simple and straight forward translation:

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");
}

You can check how it works from this other answers:

Netwave
  • 40,134
  • 6
  • 50
  • 93