Parameters and Return Values
In this page:
Function Parameters
Parameters let a function accept input values. Each parameter must be given an explicit type, since Rust never infers function signatures.
Example: Function Parameters
fn greet_person(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet_person("Ada");
}
Login to try C/C++/Java/PHP code in the editor
Returning a Value
A function's return type is declared after an arrow ->. The final expression in the function body, written without a trailing semicolon, becomes the returned value.
Example: Returning a Value
fn square(n: i32) -> i32 {
n * n
}
fn main() {
println!("Square of 6 is {}", square(6));
}
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
Functions can accept several parameters, separated by commas, each with its own type. They are used inside the function body just like local variables.
Example: Multiple Parameters
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("3 + 4 = {}", add(3, 4));
}
Login to try C/C++/Java/PHP code in the editor
Early Return with the return Keyword
The return keyword immediately exits a function with a given value, which is useful for handling special cases early before the main logic of the function runs.
Example: Early Return with the return Keyword
fn absolute_value(n: i32) -> i32 {
if n < 0 {
return -n;
}
n
}
fn main() {
println!("abs(-8) = {}", absolute_value(-8));
}
Login to try C/C++/Java/PHP code in the editor
- Adding a semicolon after the final expression in a function, which turns it from a returned value into a discarded statement.
- Forgetting to write
-> Typewhen a function is meant to return a value, causing a compile error at the return site. - Using the
returnkeyword everywhere out of habit when the idiomatic tail-expression style would be cleaner.
- Parameters are declared as
name: Typeinside the parentheses, and every parameter must have an explicit type. - A function's return type is written after
->, and the last expression (without a semicolon) is returned automatically. - The
returnkeyword can exit a function early with a value, useful inside conditionals. - A function with no return type implicitly returns the unit type
().
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: