Your First Rust Program
In this page:
fn main() {
println!("text");
}
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
// Entry point: execution of the program starts here
fn main() {
// Print "Hello, Rust!" to the console (with a trailing newline)
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.
Example: Printing with println!
// Entry point: execution of the program starts here
fn main() {
// Print "This line has a newline after it" to the console (with a trailing newline)
println!("This line has a newline after it");
// Print "So this prints on a new line" to the console (with a trailing newline)
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 in your own terminal or Node.js environment.
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
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `message`, set to `"Semicolons separate statements"`
let message = "Semicolons separate statements";
// Print "{}" to the console, substituting in `message` (with a trailing newline)
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: