In this post we are going to take our baby steps in learning Rust and the simple example of a hello world would not just cut it. We will now introduce how to Capturing User Input in Rust.

Intro

To get started we will use our trusty cargo package manager again to create a new project for us. If you have not used cargo yet, please look back at my previous post on how to setup cargo.

This will create a file system looking like below.

We will open the main.rs file and modify it. We will add a variable to hold the value of the username. One thing to remember is Rust variables default to being immutable. Once an immutable variable is assigned, you cannot change the value stored in the variable. There is also a way to explicity to make a variable as mutable and you will need to use the mut keyword for that. So lets try to add a varible named “name” like the code below.

As you can see above we have defined a variable using the let keyword and we have also defined it as mut so that is is mutable i.e change its value after creation.

You may have also noticed something as in String::new, this is how you defined a String which is a growable, heap-allocated data structure. There is also a type in Rust called str which is an immutable fixed-length UTF-8 bytes of dynamic length string somewhere in memory. If you come from a C++ or C programming lang you can think of String like std::string and str as char*, if that helps.

Getting input from terminal

Now onto how to capture input, inorder to get input one has to use the stdin library of Rust. Rust provides terminal input functions in std::io::stdin. There is a read_line function in stdin, and we need to use the use keyword to import the functionality into our program. Below is how our Rust program will look like.

So what we have done here is we are using the stdin() whcih returns an object granting access to the Standard Input. Afterwards we have called the read_line method passing in a Borrow variable with the & sign which allows changes to be made to the variable by the function. In this case we have passed in name as a Borrow variable, which creates a reference to the variable. (I will cover Borrow in later topics).

Afterwards we also have an expect function which if the program crashes Rust returns a Result object, basically you are checking that the function worked by calling expect. Lastly we are using placeholders to print the value of name. Now lets try to run the program.

As you can see above I have enter my name “Taswar” and it outputs “Hello Taswar” with a newline aftewards. We can use the trim function in String to remove it but for that I will cover in the next section of how to write a function around the input.

Summary

In this post we learned how to read user input in a terminal in Rust, in the next section we will refactor and cover how to write functions in Rust.