Menu
Coddy logo textTech

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 icon

Challenge

Easy

Write 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
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals