Rust Language : How to accept user input, trim, parse and unwrap
We write a program using Rust to take user input and display the result back to the user. This tutorial shows how to get the input, parse it, convert it to/from a string and then display it.
We begin with the io module:
“The
std::io
module contains a number of common things you’ll need when doing input and output.”
Check : https://doc.rust-lang.org/ :
The most core part of this module is the
Read
andWrite
traits, which provide the most general interface for reading and writing input and output.
Next we read the user entered string into a character array (String) on the heap.
We then trim any white space, convert to a float and set a variable ready to print
Notes :
Unwrap is required when you need there to be a value to
continue running the program
Need to use unwrap because parse returns "Result"
Trim returns a string slice with leading and trailing whitespace removed
About “unwrap”
unwrap is intended for development usage, to handle errors there is the “Result” enum which can be handled with “Ok” and “Err”
enum Result<T, E> {
Ok(T),
Err(E),
}
- https://doc.rust-lang.org/std/io/
- https://doc.rust-lang.org/std/primitive.str.html#method.parse
- https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap
- https://doc.rust-lang.org/std/primitive.str.html#method.trim
Copy and try out the code:
use std::io;
fn main() {
println!("Enter your weight (in kg): ");
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let weight: f32 = input.trim().parse().unwrap();
println!("{}", weight);
}