Today, we will focus on creating a Rust function called greet_user
that takes a user's name as a parameter, reads input from the terminal, and prints a personalized greeting message.
In Rust, a function is defined using the fn
keyword followed by the function name, parameters, return type (if any), and the function body enclosed in curly braces {}
. Let's break down the structure of the greet_user
function:
Here
fn
: Keyword indicating the start of a function definition.
greet_user
: Name of the function.
(name :&str)
: Parameter list enclosed in parentheses ()
name
: Name of the parameter.
&str
: Type of the parameter, indicating a string slice.
The main function is the entry point of a Rust program.It contains the code that will be executed when the program is run.
println!("Enter the name ");
: Prints a message asking the user to enter a name.
let mut userName = String::new();
: Declares a mutable variable userName of type String to store the user's input.
std::io::stdin().read_line(&mut userName).expect("Something error happened");
-
Reads a line from the standard input (keyboard) and stores it in the
userName
variable.&mut userName
passes a mutable reference to userName to allow the read_line function to modify its contents.expect("Something error happened");
handles any potential errors that may occur during the input operation.
greet_user(&userName);
: Calls the greet_user function with a reference to the userName variable as an argument.
Passing a reference (&
) to userName
allows greet_user
to access the value without taking ownership of it.
Now when we run this code the output will be
To avoid the problem of newline character causing the ouput template string to be in newline after the template word , we need to trim out the user input
so for that the code should be modified like wise
Here the user input is trimmed before passing it to greet_user
, any leading or trailing whitespace will be removed.
The to_string()
method is used to convert a string slice (&str
) to an owned String
.This conversion is necessary because greet_user expects a &str
parameter, and to_string()
creates a new String
instance from the trimmed input
Now the final output will look like
so that's all for this challenge , Thank You
For a more detailed explanation, you can watch my YouTube video.
GitHub - Link