Rust : Important Concepts

Void Functions vs Diverging Functions

There are two kinds of functions that doesn’t return any value

#1.  fn void_function() {} 

#2.  fn diverging_function() -> ! {}

#1 A Void function doesn’t have any any return doens’t mean it doesn’t return any value, it returns () type. This is equivalent to void in C/C++.

fn void_function() -> () {}

#2 A diverging function is guarenteed to not return anything ie. println!("sample text");

Example of diverging functions is

fn diverging_function() -> ! {
   panic!()
}

fn diverging_function_2() -> ! {
    loop{}
}

Comparing with other languages, its similar to returning Exception in other languages. In languages like Java, even if the function return some data type, and due to exception it returns some Exception. The data type is different from what is output, since java doens’t have a way to mark it as actual method as diverging. Instead, Rust has special construct to specify nothing is returning ie. specify the function as diverging, which has similar effect.

public String getString(String val){
     if (val == null){
           throw Exception();
     }
     return new String(val);
}

Next: Stack Unwinding