Continuting on from where we left off, in this post I will refactor my code to use a function such that I can reuse my code later on. I will showcase how to write Functions in Rust with VSCode.

Intro

If we look at our previous post we have a very simple main function and it is just getting user input and then it outputs it with the println method. Its not one of the most elegant code but we we taking baby steps here. As a preview of our code code, it looks like below.

Now we would like to extract the read_line into its own function, the way we will do it is like below, I will explain in details after the code sample.

What I have done is create a function with the fn keyword and named it get_name, afterwards you see a -> character which tells the function that it will be returning a String.

You do not need a return statement in Rust the last value in the function acts as a return value

I have also called the trim function, the only issue is it returns a str rather than a String so I have to call to_string() in order to convert it back to String.

pub fn trim(&self) -> &str
Returns a string slice with leading and trailing whitespace removed.

If we run the program we will see this kind of output.

Now I dont know if you are like me, but I don’t like the output of this code, the input readline is right after the print statement. I would like to have the input right at the first line where it states “Pleaes enter your name:”. Let’s try to modify our code so that we can get the input in the same line.

What you see is I have first imported std::io::{self, Write};. So what this does is it imports std::io; and also use std::io::Write;. Therefore we can use the call for io::stdout().flush().unwrap();, since we imported std::io also.

Now if we run the program, we will get the code formatted in the way we want to.

Summary

So we have seen how to refactor our code into a function and in our next section lets build on this concept but change it to a game as simple as Rock, Paper, Scissors.