To create a function in Rust, you need to first declare the function with its name, input parameters, output type, and the code block containing the steps or operations to be executed by the function. Here is an example of a simple function that takes two integer inputs and returns their sum:
fn add_numbers(x: i32, y: i32) -> i32 {
let sum = x + y;
sum
}
In the above code, we have defined a function with the name ‘add_numbers‘ that takes two integer inputs ‘x‘ and ‘y‘. The output type of the function is also ‘i32‘ (integer). Inside the code block, we have performed the addition operation and stored the result in the variable ‘sum‘. Finally, we are returning the value of ‘sum‘ as the output of the function.
To use this function in our main code, we can call it as follows:
fn main() {
let result = add_numbers(10, 20);
println!("The sum is {}", result);
}
In the above code, we have called the ‘add_numbers‘ function with the inputs ‘10‘ and ‘20‘, and stored the result in the variable ‘result‘. Finally, we have printed the output using the ‘println‘ function. The output of the program will be:
The sum is 30