Simple Rust examples 🔗

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

Prompting for user input 🔗

This function asks the user a question, and returns the answer as a String:

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()