Defining and Calling Functions in Rust
Defining and Calling Functions
70
Functions are a fundamental programming concept that allows developers to organize code and make it more modular. In this course on Rust, we will learn how to define and call functions.
Defining a function means creating a block of code that performs a specific task. In Rust, functions are defined with the fn
keyword, followed by the function name and a set of parentheses that may include parameters. The function block is then enclosed in curly braces {}
.
For example, the following code defines a simple function that takes two integer parameters and returns their sum:
fn add_numbers(a: i32, b: i32) -> i32 { let result = a + b; return result; }
To call a function, we use its name followed by parentheses. If the function requires arguments, we pass them inside the parentheses.
For example, to call the add_numbers
function defined above, we would use the following code:
let sum = add_numbers(2, 3);
This code assigns the value 5
to the variable sum
, which is returned by the add_numbers
function.
In Rust, functions can also be defined as "methods", which are functions that are associated with a particular struct or enum. Method calls are similar to regular function calls, but the method name is preceded by the name of the struct or enum that the method belongs to.
By understanding how to define and call functions in Rust, we gain the ability to write cleaner, more maintainable code.
March 27, 2023