]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/fn.md
New upstream version 1.39.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / fn.md
CommitLineData
2c00a5a8
XL
1# Functions
2
3Functions are declared using the `fn` keyword. Its arguments are type
4annotated, just like variables, and, if the function returns a value, the
5return type must be specified after an arrow `->`.
6
7The final expression in the function will be used as return value.
8Alternatively, the `return` statement can be used to return a value earlier
9from within the function, even from inside loops or `if`s.
10
11Let's rewrite FizzBuzz using functions!
12
13```rust,editable
14// Unlike C/C++, there's no restriction on the order of function definitions
15fn main() {
16 // We can use this function here, and define it somewhere later
17 fizzbuzz_to(100);
18}
19
20// Function that returns a boolean value
21fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
22 // Corner case, early return
23 if rhs == 0 {
24 return false;
25 }
26
27 // This is an expression, the `return` keyword is not necessary here
28 lhs % rhs == 0
29}
30
31// Functions that "don't" return a value, actually return the unit type `()`
32fn fizzbuzz(n: u32) -> () {
33 if is_divisible_by(n, 15) {
34 println!("fizzbuzz");
35 } else if is_divisible_by(n, 3) {
36 println!("fizz");
37 } else if is_divisible_by(n, 5) {
38 println!("buzz");
39 } else {
40 println!("{}", n);
41 }
42}
43
44// When a function returns `()`, the return type can be omitted from the
45// signature
46fn fizzbuzz_to(n: u32) {
47 for n in 1..n + 1 {
48 fizzbuzz(n);
49 }
50}
83c7162d 51```