Skip to content

Commit 86b8f3f

Browse files
committed
Add section about diverging functions
1 parent 446a322 commit 86b8f3f

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
- [Iterator::any](fn/closures/closure_examples/iter_any.md)
7171
- [Iterator::find](fn/closures/closure_examples/iter_find.md)
7272
- [Higher Order Functions](fn/hof.md)
73+
- [Diverging functions](fn/diverging.md)
7374

7475
- [Modules](mod.md)
7576
- [Visibility](mod/visibility.md)

src/fn/diverging.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Diverging functions
2+
3+
Diverging functions never return. Their return type in Rust is denoted by `!`, which is an empty type. As opposed to all the other types, this one cannot be instantiated, because the set of all possible values this type can have is empty. Note, that it is different from the `()` type, which has exactly one possible value.
4+
5+
6+
For example, this functions returns as usual, although there is no information in the return value.
7+
```rust
8+
fn main() {
9+
fn some_fn() {
10+
()
11+
}
12+
13+
let a: () = some_fn();
14+
println!("This functions returns and you can see this line.")
15+
}
16+
```
17+
18+
As opposed to this function, which will never return the control back to the caller.
19+
```rust
20+
#![feature(never_type)]
21+
22+
fn main() {
23+
let x: ! = panic!("This call never returns.");
24+
println!("You will never see this line!");
25+
}
26+
```
27+
28+
Although this might seem like an abstract concept, it is in fact very useful and often handy. The main advantage of this type is that it can be cast to any other one and therefore used at places where an exact type is required, for instance in `match` branches. This allows us to write code like this:
29+
30+
```rust
31+
fn main() {
32+
fn sum_odd_numbers(up_to: u32) -> u32 {
33+
let mut acc = 0;
34+
for i in 0..up_to {
35+
let addition: u32 = match i%2 == 1 {
36+
true => i,
37+
false => continue,
38+
};
39+
acc += addition;
40+
}
41+
acc
42+
}
43+
println!("Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9));
44+
}
45+
```
46+
47+
It is also the return type of functions that loop forever (e.g. `loop {}`) like network servers or functions that terminates the process (e.g. `exit()`).
48+
49+
50+

src/macro/syntax.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Syntax

0 commit comments

Comments
 (0)