Rust Functions and Parameters
Introduction to Rust Functions
In Rust, functions are used to make code modular and enhance functionality. Functions are named blocks of code that perform a specific task. In this post, we will examine how functions are defined in Rust, how parameters are used, and the return values of functions.
Defining Functions
To define a function in Rust, the fn keyword is used. The function is defined with its name, parameters, and return type. Let's go through a simple example.
fn hello_world() {
println!("Hello, World!");
}
In the code above, we define a function called hello_world. When this function is called, it prints "Hello, World!" to the screen.
Defining Functions with Parameters
Functions can be made more dynamic by taking certain parameters. Parameters are specified in the function definition along with a specific data type. For example, we can create a function that adds two numbers:
fn add(a: i32, b: i32) -> i32 {
a + b
}
Here, a and b are two integers (i32) passed to the function. The function's return type is specified with the -> symbol.
Using Functions
Calling the functions we've defined is quite simple. Below is an example showing how we can use the add function:
fn main() {
let result = add(5, 7);
println!("Result: {}", result);
}
In this example, the add function takes 5 and 7 and returns the sum of these two numbers. The result is assigned to the result variable and then printed to the screen.
Conclusion
In Rust, functions are critically important for increasing code reusability and supporting the modular structure of the program. By enriching our functions with parameters, we can make them more flexible. In this post, we tried to provide basic information about Rust functions and parameters, and aimed to explain them with examples. Understanding how functions work when programming with Rust will help you write more effective and clean code.

Yorum Gönder