Recently I started learning Rust and was building a command line application, and wanted to accept user input from the terminal. After a couple of Google searches, I landed on the Rust docs for the standard input/output module which allows you to perform this task. In this post, we'll go through all my learnings. We'll understand how we can use this crate to read the user input from the terminal or command prompt and store this value inside a variable.
We'll get started by importing std::io crate in our application.
use std::io
Next inside our main function, we'll declare a new string which we'll use to hold the user input read from the console.
let mut value: String = String::new();
Also, let's print a message to the user, asking for their names.
println!("What is your name?");
To actually get the input we're going to use the match statement along with the read_line method.
match io::stdin().read_line(&mut value) {
Ok(_) => {
println!("Hello {}", value);
}
Err(e) => {
println!("Something went wrong!");
println!("{}", e);
}
}
The read_line method will return a result that can be either success or failure and we're using the match statement to determine the result and perform appropriate action based on the result. If the result is a success, we'll simply print the hello message. And in case of an error, we'll simply dump the error on the console.
And that is it!
Adding it all together we get the following program.
use std::io;
fn main() {
let mut value: String = String::new();
println!("What is your name?");
match io::stdin().read_line(&mut value) {
Ok(_) => {
println!("Hello {}", value);
}
Err(e) => {
println!("Something went wrong!");
println!("{}", e);
}
}
}
When you run the above program, you'll be prompted to enter your name. And if you've done everything correctly after entering your name, you'll see the hello message.
I hope you found this tutorial useful. In case you've any queries or feedback, feel free to drop a comment.
Must Read: How to Add a Comments Section to Your Gatsby Blog