Diverging functions

Diverging functions never return. They are marked using !, which is an empty type.

  1. fn foo() -> ! {
  2. panic!("This call never returns.");
  3. }

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.

For example, this functions returns as usual, although there is no information
in the return value.

  1. fn some_fn() {
  2. ()
  3. }
  4. fn main() {
  5. let a: () = some_fn();
  6. println!("This functions returns and you can see this line.")
  7. }

As opposed to this function, which will never return the control back to the caller.

  1. #![feature(never_type)]
  2. fn main() {
  3. let x: ! = panic!("This call never returns.");
  4. println!("You will never see this line!");
  5. }

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:

  1. fn main() {
  2. fn sum_odd_numbers(up_to: u32) -> u32 {
  3. let mut acc = 0;
  4. for i in 0..up_to {
  5. // Notice that the return type of this match expression must be u32
  6. // because of the type of the "addition" variable.
  7. let addition: u32 = match i%2 == 1 {
  8. // The "i" variable is of type u32, which is perfectly fine.
  9. true => i,
  10. // On the other hand, the "continue" expression does not return
  11. // u32, but it is still fine, because it never returns and therefore
  12. // does not violate the type requirements of the match expression.
  13. false => continue,
  14. };
  15. acc += addition;
  16. }
  17. acc
  18. }
  19. println!("Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9));
  20. }

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()).