In Rust, functions are the basic building blocks of code, used to encapsulate reusable logic. Every Rust program contains at least one main
function, which is the entry point of the program. This article will detail how to define and call functions, including key concepts such as parameter passing and return values.
Basic Definition of Functions
Use the fn keyword to define a function, followed by the function name, parameter list, and return type. The function body is wrapped in curly braces {}
. For example, define a simple function to print a greeting:
fn greet() {
println!("Hello, Rust!");
}
In this example, the greet function has no parameters and no return value; it simply performs a print operation. To call this function, just write the function name followed by parentheses in the code:
fn main() {
greet(); // Call the greet function
}
Note: In Rust, function names typically use snake_case, for example
calculate_sum.
Parameters and Return Values
Functions can accept parameters and return values. Parameters are declared in parentheses after the function name, and each parameter needs to specify its type. The return type is specified after the parameter list using the -> symbol. For example, define a function to calculate the sum of two integers:
fn add(x: i32, y: i32) -> i32 {
x + y // In Rust, the last expression is automatically used as the return value, no need for the return keyword
}
You can also use the return keyword to return a value:
fn add(x: i32, y: i32) -> i32 {
return x + y; // Use return to return
}
When calling this function, you need to pass two integer parameters:
fn main() {
let result = add(5, 3);
println!("Sum: {}", result); // Output: Sum: 8
}
If a function has no return value, you can omit the -> part, or specify the return type as () (unit type). For example:
fn print_message(msg: &str) {
println!("{}", msg);
}
Function Nesting
Functions can be defined inside other functions, but the scope of inner functions is limited to the outer function. For example:
fn outer() {
fn inner() {
println!("Inner function");
}
inner(); // Can only be called within the outer function
}
Note: Avoid defining too many nested functions within a function, as this may make the code difficult to maintain. It is generally recommended to split logic into separate functions.