Simple Rust examples ๐Ÿ”—

Here are some simple examples of Rust syntax... If you're beginning Rust programming, you may find them useful.

Prompt and receive user input on the same line ๐Ÿ”—

This function asks the user a short question without printing a newline, so the answer is provided on the same line as the query. This is natural prompt behavior for interactive CLIs.. or text adventure games.

fn prompt_user(prompt: String) -> String {
    // Prompt user with a String, return the result as a String.
    print!("{prompt}: ");
    // Must flush output because there was no newline.
    io::stdout().flush().unwrap();
    // Get the answer and return it...
    let mut answer = String::new();
    io::stdin().read_line(&mut answer).expect("Failed to read line");
    answer
}

Uses: print!, std::io::stdout().flush(), io::stdin().read_line()