Horje
Rust - Diverging Functions

In Rust, we have a concept of diverging functions. Diverging functions are unique function that returns neither value nor anything else. For declaring a function as diverging, we use a keyword named panic! that is a macro in Rust (similar to println! macro). While println! macro is responsible for formatting a print statement onto a new line, panic! macros are accountable for crashing the thread of program execution with an error message like thread main panic and hence it does not return apart from printing the string text in the console.

Syntax:

fn diverging_function_name() -> ! {
   panic!(“This function does not return anything”);
// code defined 

}

Example 1:

Rust

// Rust code for diverging function
fn main()
{
    gfg_diverging_function();
}
fn gfg_diverging_function() -> ! 
{
   panic!("This function panics during the thread execution!");
}

Output:

 

Explanation:

In this example, we can clearly see that once we use the panic! keyword then Rust panics during execution. As they are marked by !, these functions are generally empty and do not return values. In this function, we have declared an function gfg_diverging_function in the main method and while calling that method we can see the error attached in the output.




Reffered: https://www.geeksforgeeks.org


Rust

Related
Rust - Phantom Type Parameter Rust - Phantom Type Parameter
Rust - Multiple Bounds Rust - Multiple Bounds
Rust - The newtype Idiom Rust - The newtype Idiom
Rust - Struct Visibility Rust - Struct Visibility
Rust - Bounds Rust - Bounds

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12