Your first program
| fn main | |
| println! macro | |
| Compile and run | |
| Common beginner mistakes |
fn main
Every runnable Rust program starts in the main function.
The fn keyword introduces the function, main is its fixed name, and the braces hold the statements that run in order.
fn main() {
println!("Hello, Rust");
}
println! macro
Output uses the println macro, not a plain function.
The mark at the end of the name shows a macro call, and the text in quotes supports {} placeholders for values.
fn main() {
println!("Hello, Rust");
println!("2 + 3 = {}", 2 + 3);
}
cargo run
Hello, Rust
Compile and run
A single file program can be built directly with rustc and then started by name.
Inside a cargo project the shorter cargo run command does both steps at once.
rustc main.rs
./main
Hello, Rust
Common beginner mistakes
Macros that print end with the mark, such as println.
Without the mark the compiler looks for a function with that name and fails, so keep the mark every time.
Statements also end with a semicolon, which is why every print line above ends with one.
Next: Variables
Article author: Arthur Isaev