Parameters and Arguments
Part of the Fundamentals section of Coddy's Rust journey — lesson 50 of 75.
An argument in a function is a value that you pass into the function when you call it. To add arguments to a function we write them inside the parenthesis ():
fn function_name(arg1: data_type, arg2: data_type, ...) {
// code
}We can name the arguments as we want and we can write as many arguments as we need.
To call a function and pass arguments to it we write:
function_name(value1, value2, value3, ...);Passing too many arguments to a function that is expecting less arguments will cause the program to fail
Example of usage:
fn is_even(number: i32) {
if number % 2 == 0 {
println!("{} is even", number);
} else {
println!("{} is odd", number);
}
}
for i in 15..34 {
is_even(i);
}
for i in 153..219 {
is_even(i);
}Here we have a function called is_even that accepts one argument called number and print if the number is even or odd. Then we call the function twice: one time for all the numbers between 15 and 34, Second time for all numbers between 153 and 219.
Challenge
EasyWrite a program that gets two input numbers. The input numbers are the arguments of the function.
Create a function that gets two arguments, calculates the product of them and prints it, name the function however you like.
Call the function with the input numbers.
Note! In your code, write the function before it's call/execution statements.
Cheat sheet
To add arguments to a function, write them inside the parentheses with their data types:
fn function_name(arg1: data_type, arg2: data_type) {
// code
}Call a function by passing values as arguments:
function_name(value1, value2);Example with one argument:
fn is_even(number: i32) {
if number % 2 == 0 {
println!("{} is even", number);
} else {
println!("{} is odd", number);
}
}
is_even(42);Passing too many arguments to a function will cause the program to fail
Try it yourself
use std::io;
// Function declaration
fn main() {
let mut input_a = String::new();
let mut input_b = String::new();
io::stdin().read_line(&mut input_a).unwrap();
io::stdin().read_line(&mut input_b).unwrap();
let a: i32 = input_a.trim().parse().unwrap();
let b: i32 = input_b.trim().parse().unwrap();
// Call the function with a and b as arguments
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Functions
Declaring FunctionsParameters and ArgumentsReturn ValuesMultiple Return ValuesRecap - Sigma FunctionRecap - Validation Function3Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input