Skip to content

Latest commit

 

History

History
42 lines (31 loc) · 1.83 KB

File metadata and controls

42 lines (31 loc) · 1.83 KB

Understanding Functions in Rust

Creating Functions: The fn Keyword

  • Functions are declared using the fn keyword, 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.

Example: Adding Two Numbers

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:

  1. The main function defines two variables, a and b, with values 10 and 20 respectively.
  2. It calls the do_sum function with arguments a and b, passing their values.
  3. The do_sum function takes two i32 arguments (a and b) and returns an i32 value.
  4. Inside do_sum, the values of a and b are added, and the result is returned.
  5. The main function receives the return value of do_sum (the sum) and stores it in the sum variable.
  6. Finally, main prints the sum of a and b.

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