0
0
Rustprogramming~10 mins

main function and entry point in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - main function and entry point
Program starts
Look for main()
Execute main() body
Program ends
Rust programs start by running the main() function, which is the entry point where execution begins and ends.
Execution Sample
Rust
fn main() {
    println!("Hello, world!");
}
This program starts at main(), prints a message, then ends.
Execution Table
StepActionCode LineOutput
1Program starts and looks for main()fn main() {
2Enter main functionfn main() {
3Execute println! macroprintln!("Hello, world!");Hello, world!
4End of main function reached}
5Program terminates
💡 Reached end of main(), program stops
Variable Tracker
VariableStartAfter main startAfter println!Final
No variables----
Key Moments - 3 Insights
Why does Rust need a main() function?
Rust uses main() as the fixed starting point for running code, as shown in execution_table step 1 and 2.
What happens if main() is missing?
The program will not compile because Rust requires main() as the entry point, so it cannot start execution.
Does main() return a value?
By default, main() returns () (unit type), meaning no value is returned, and the program ends after main() finishes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 3?
Amain()
BHello, world!
CProgram starts
DNo output
💡 Hint
Check the Output column at step 3 in execution_table
At which step does the program finish running main()?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the Action column where it says 'End of main function reached'
If you remove main(), what happens?
AProgram prints Hello, world! anyway
BProgram compiles but does nothing
CProgram fails to compile
DProgram runs but crashes
💡 Hint
Refer to key_moments about missing main() function
Concept Snapshot
Rust programs start execution at the main() function.
main() is the required entry point.
Code inside main() runs sequentially.
Program ends when main() finishes.
Use println! to print output inside main().
Full Transcript
In Rust, the program always starts by running the main() function. This is the entry point where the computer begins executing your code. When the program runs, it looks for main(), then runs the code inside it step by step. For example, if main() calls println!("Hello, world!"), it prints that message to the screen. After main() finishes, the program ends. If main() is missing, the program will not compile because Rust requires this function to know where to start. The main() function does not return a value by default; it just signals the program to stop when done.