0
0
Rustprogramming~5 mins

main function and entry point in Rust

Choose your learning style9 modes available
Introduction

The main function is where a Rust program starts running. It tells the computer what to do first.

When you want to create a program that runs some instructions.
When you need a starting point for your Rust application.
When you want to organize your code so it runs in order.
When you want to print messages or perform tasks when the program starts.
Syntax
Rust
fn main() {
    // code to run
}

The main function has no parameters and no return value by default.

It is the required entry point for every executable Rust program.

Examples
This program prints a greeting message when it runs.
Rust
fn main() {
    println!("Hello, world!");
}
This program stores a number and prints it.
Rust
fn main() {
    let x = 5;
    println!("x is {}", x);
}
Sample Program

This simple program shows how the main function runs and prints a message.

Rust
fn main() {
    println!("Welcome to Rust!");
}
OutputSuccess
Important Notes

You can only have one main function in a Rust executable.

If you want to return an error code, you can change the return type to Result<(), Box>.

Summary

The main function is the starting point of a Rust program.

It runs automatically when you start your program.

Use it to organize what your program does first.