Your First Rust Program
In this page:
The main Function
Every executable Rust program must have a function named main. This is the entry point: when you run the compiled program, execution starts at the first line inside main and proceeds top to bottom.
Example: The main Function
fn main() {
println!("Hello, Rust!");
}
Login to try C/C++/Java/PHP code in the editor
Printing with println!
println! is a macro, not a regular function -- that is why it ends with an exclamation mark. It prints its argument to standard output followed by a newline character, making it the most common way to see output from a Rust program.
Note: Macros like println! can accept a variable number of arguments, which regular Rust functions cannot do.
Example: Printing with println!
fn main() {
println!("This line has a newline after it");
println!("So this prints on a new line");
}
Login to try C/C++/Java/PHP code in the editor
Compiling and Running
You turn Rust source code into a runnable program with the rustc compiler, which produces a native executable. You then run that executable directly from the command line.
Example: Compiling and Running
rustc main.rs
./main
⚠️ Run this command in your terminal.
Statements End With Semicolons
Most lines of code inside a Rust function are statements, and Rust requires each one to end with a semicolon. Forgetting a semicolon is one of the most common early compiler errors.
Example: Statements End With Semicolons
fn main() {
let message = "Semicolons separate statements";
println!("{}", message);
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the semicolon at the end of a statement, which Rust requires unlike some scripting languages.
- Naming the file something other than what you pass to
rustc, then wondering why the compiler can't find it. - Forgetting that
mainis the required entry point function name -- Rust always starts running fromfn main().
- Every Rust program needs a
mainfunction, which is where execution begins. println!is a macro (note the!) used to print text followed by a newline.- Source files end in
.rsand are compiled withrustc filename.rs, producing an executable. - Statements in Rust end with a semicolon.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: