Functions
You declare a function as follows:
fn say_hello() { println!("Hello"); } fn main() { say_hello(); }
Functions with parameters
fn main() { print_sum(5, 7); } fn print_sum(number1: i32, number2: i32) { println!("Sum of {} and {} is {}", number1, number2, number1 + number2); }
Statements vs Expressions
In Rust,
- Statements don't return a value
- Expressions always evaluate to a value
Returning a value from a function
When returning a value from a function, you would typically do so using the last expression in the function. In this case, you must not end it with a semicolon. Example:
fn main() { let num1 = 5; let num2 = 7; let sum = sum(5, 7); println!("Sum of {} and {} is {}", num1, num2, sum); } fn sum(number1: i32, number2: i32) -> i32 { number1 + number2 }
If you were to end the last line above with a semicolon (as shown below), that line becomes a statement, and you'll get an error.
fn main() { let num1 = 5; let num2 = 7; let sum = sum(5, 7); println!("Sum of {} and {} is {}", num1, num2, sum); } fn sum(number1: i32, number2: i32) -> i32 { number1 + number2; }
In the above, you get an error about the unit type: ()
. This means that you're trying to use a statement where an expression is expected.
Statements don't return a value , which is expressed by the ()
, the unit type.
Lastly, you can return from a function early using return
keyword and specifying a value. That is, before the function's last line, for example, from the body of an if block within the function.
fn main() { let number1 = 3; let number2 = 5; let number3 = 15; let number4 = 16; println!("{}", fizz_buzz(number1)); println!("{}", fizz_buzz(number2)); println!("{}", fizz_buzz(number3)); println!("{}", fizz_buzz(number4)); } fn fizz_buzz(number: i32) -> String { if number % 15 == 0 { return String::from("Fizz Buzz"); } else if number % 5 == 0 { return String::from("Buzz"); } else if number % 3 ==0 { return String::from("Fizz"); } number.to_string() }