Open In App

Rust – Diverging Functions

Last Updated : 22 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads