Functions are a fundamental building block in Rust, as in any programming language. They allow you to encapsulate logic and reuse code, making your programs more modular and easier to understand. In this challenge, you will define and implement a series of simple functions that perform basic operations.
Your task
Your task is to define three functions:
add(a: i32, b: i32) -> i32- This function should return the sum ofaandb.subtract(a: i32, b: i32) -> i32- This function should return the difference betweenaandb.multiply(a: i32, b: i32) -> i32- This function should return the product ofaandb.
You need to complete these functions so that they correctly perform the specified operations.
Example
let result = add(2, 3);assert_eq!(result, 5);let result = subtract(5, 3);assert_eq!(result, 2);let result = multiply(2, 3);assert_eq!(result, 6);
Hints
- You can define a function in Rust using the
fnkeyword followed by the function name, parameters in parentheses, and the return type. - Use the
returnkeyword or just the last expression in the function body to return a value. - Make sure you use the
pubkeyword to make your functions public so they can be accessed from other modules. - Make sure your function signatures match the required signatures exactly.
← PreviousNext →
pub fn add(a: i32, b: i32) -> i32 {// Step 1: implement addition}// Step 2:// Define a public function named `subtract`// that accepts two arguments of type `i32`// and returns an `i32`.// make sure you make the function public by using the `pub` keyword.// Step 3:// Define a public function named `multiply`// that accepts two arguments of type `i32`// and returns an `i32`.// make sure you make the function public by using the `pub` keyword.