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()
Print an arbitrary number of digits from an f64 🔗
In this case, I just want to print a number of digits from the PI
constant in Rust's standard
library:
fn print_pi() {
// Get a string representation of π. I've chosen 48 digits, which is the max for this data type.
let pi_str: String = format!("{0:.48}", std::f64::consts::PI);
// The number of decimal places that can be printed depends on the size of the string.
let max_val: usize = pi_str.len()-2;
// Prompt the user for input.
let answer: String = prompt_user(
format!("Decimal places of π to print? [0-{max_val}]"));
let mut width: usize = answer.trim().parse().expect("You didn't enter a number!");
// Constrain the result to max_val.
if width > max_val {
width = max_val;
}
// Print it!
println!("{}", &pi_str[0..width+2]);
}
Uses: Prompting for user input, std::f64::consts::PI, format!, println!
Output:
Decimal places of π to print? [0-48]: 16
3.1415926535897931