Start learning free

LESSON 40 OF 348 · FUNCTIONS I

Why Parameters & Arguments in Rust

Lesson

Now that we've learned about function parameters and arguments, let's see why they are so important in our prgrammers' life:

Consider this: Three students named Andy, Mike and Sally made a mistake. And so their teacher asked each of them to write an apology on the whiteboard.

We can put the apologies in a program like this:

println!("This is Andy");
println!("Andy made a mistake");
println!("Andy suffers the consequences");

println!("This is Mike");
println!("Mike made a mistake");
println!("Mike suffers the consequences");

println!("This is Sally");
println!("Sally made a mistake");
println!("Sally suffers the consequences");

That's decent. But what if we want to change the students' names?

We would have to go through the whole program and change each individual name with the new one.

And if we dealt with 10 students instead of 3 and if the apology text consisted of more than 3 lines, this would quickly get out of hand.


The story with functions:

This is where functions with parameters shine. We can write a function that takes in a student's name as argument and prints the specific aplogy for that student.

Then, we'll just call the function for each individual student:

fn print_message(name: &str) {
	println!("This is {}", name);
	println!("{} made a mistake", name);
	println!("{} suffers the consequences", name);
}

print_message("Andy");
print_message("Mike");
print_message("Sally");

Changing the story:

Need to change the students' names? We only change the arguments in the function calls.

Need to change the aplogy text a little bit? We only change it inside the function instead of changing it in the whole program.

fn print_message(name: &str) {
	println!("This is the apology of {}", name);
	println!("{} made a mistake and so {} suffers the consequences", name, name);
}

print_message("Andrei");
print_message("Paul");
print_message("Mary");

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    Why Parameters And Arguments in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free