Functions

Functions are declared using the fn keyword. Its arguments are type
annotated, just like variables, and, if the function returns a value, the
return type must be specified after an arrow ->.

The final expression in the function will be used as return value.
Alternatively, the return statement can be used to return a value earlier
from within the function, even from inside loops or ifs.

Let’s rewrite FizzBuzz using functions!

  1. // Unlike C/C++, there's no restriction on the order of function definitions
  2. fn main() {
  3. // We can use this function here, and define it somewhere later
  4. fizzbuzz_to(100);
  5. }
  6. // Function that returns a boolean value
  7. fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
  8. // Corner case, early return
  9. if rhs == 0 {
  10. return false;
  11. }
  12. // This is an expression, the `return` keyword is not necessary here
  13. lhs % rhs == 0
  14. }
  15. // Functions that "don't" return a value, actually return the unit type `()`
  16. fn fizzbuzz(n: u32) -> () {
  17. if is_divisible_by(n, 15) {
  18. println!("fizzbuzz");
  19. } else if is_divisible_by(n, 3) {
  20. println!("fizz");
  21. } else if is_divisible_by(n, 5) {
  22. println!("buzz");
  23. } else {
  24. println!("{}", n);
  25. }
  26. }
  27. // When a function returns `()`, the return type can be omitted from the
  28. // signature
  29. fn fizzbuzz_to(n: u32) {
  30. for n in 1..n + 1 {
  31. fizzbuzz(n);
  32. }
  33. }