In Rust, we begin functions using fn
.
In Rust, we begin functions using fn
.
Here's a basic function called sing
that prints a String
:
fn sing() {
println!("la la la LA LA");
}
Functions can take inputs and give back outputs.
Here's how you can make a function called add
that takes two numbers and returns their sum:
fn add(x: i32, y: i32) -> i32 {
x + y
}
In Rust, a function's last expression is automatically its returned value, as long as it's not followed by a semicolon.
For example, the following function returns the square of a number.
fn square(x: i32) -> i32 {
x * x
}
let result = square(3);
println!(result); // 9
What if you add a semicolon to the last expression?
If you add a semicolon to the end of a function's last expression, it makes the function return ()
. If the function signature specifies a different return type, you'll encounter a compile-time error.
For instance:
fn square(x: i32) -> i32 {
// x * x; Error! Expected return type `Integer` but found `()`
}
return
keywordIf you prefer to be explicit with your return statements, Rust still supports using the return
keyword.
fn square(x: i32) -> i32 {
return x * x; // <-- also valid!
}
Whether you choose to use the return
keyword boils down to personal preference.
Function declaration: Functions are declared using the fn
keyword with typed arguments. Return types are defined using the ->
notation.
Expressive return mechanism: In Rust, the value of the final expression in a function serves as its return value, provided it doesn't end with a semicolon. Ending an expression with a semicolon causes it to return ()
, an empty tuple.
Explicit return
keyword: Rust allows the use of the return
keyword for early exits or clarity, but it's optional when returning the value of the final expression.
For a more comprehensive understanding of Rust's functions, consider referring to the Rust book.