Rust main() Function

Rust Main Function

In the Rust language, the main() function is used to signal the start of program execution and to control flow throughout the program.

The main() function is declared using standard function syntax:

fn main() {}

The main() function is still a function, but it’s different from user defined functions in several ways.

The primary unique factor of the main() function is it’s role in governing program execution. In addition, the main() function can’t take any arguments so we cannot use parameters in the main() function declaration.

For a long time, the main() function could not return any value but as of Rust 1.26, it can return a result.

What is the main() Function?

The main() function primarily does two things:

  1. It signals the start of program execution: program execution is said to begin with the main() function.
  2. It directs program execution. The flow of execution follows the code of the main() function. User defined functions can be written outside of the main function, but they must be called from within the main() function. This is how the main() function helps to govern control flow.

Working With The main() Function

For simple applications, the safest and easiest thing to do is to place all code inside of the main() function. You can call functions that live outside the main() function, but this isn’t good practice unless there is a reason to.

The reason is that functions that live outside the main() function have global scope. We should always limit scope as much as possible, because this helps us to increase the safety of our code.

This is why Rust tends to throw a lot of compiler errors when attempting to use functions with global scope, and also why variables can’t be global scope (although constants can).