- Functions are declared using the
fnkeyword, followed by a name, arguments, and a return type. - Arguments allow you to pass values into the function for processing.
- The return type specifies the data type the function will return.
fn main() {
let a: i32 = 10;
let b = 20;
let sum = do_sum(a, b); // Call the function with arguments
println!("Sum of {} and {} = {}", a, b, sum);
}
fn do_sum(a: i32, b: i32) -> i32 { // Define a function named do_sum
return a + b; // Return the sum of a and b
}Explanation:
- The
mainfunction defines two variables,aandb, with values10and20respectively. - It calls the
do_sumfunction with argumentsaandb, passing their values. - The
do_sumfunction takes twoi32arguments (aandb) and returns ani32value. - Inside
do_sum, the values ofaandbare added, and the result is returned. - The
mainfunction receives the return value ofdo_sum(the sum) and stores it in thesumvariable. - Finally,
mainprints the sum ofaandb.
Benefits of Functions
- Code Reuse: Functions can be called multiple times from different parts of your program, promoting code reusability and reducing redundancy.
- Modularity: Functions break down complex tasks into smaller, manageable units, improving code organization and readability.
- Data Encapsulation: Functions can encapsulate specific logic and data, making it easier to control data flow and maintain state within the application.
Further Learning
- The Rust Programming Language Book: https://doc.rust-lang.org/book/
- Rust by Example: https://doc.rust-lang.org/rust-by-example/