Rust is a powerful language that offers unique features for system-level programming. Let's dissect a simple Rust program to understand its anatomy.
The Main Function
Every Rust program begins with the `main` function. This function is always the first code that runs in every executable Rust program. Here's how it looks:
Rust
fn main() {
}
The `main` function is defined with no parameters and returns nothing. If there were parameters, they would go inside the parentheses `()`. The function body is wrapped in `{}`. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between.
The Body of the Main Function
The body of the `main` function holds the following code:
Rust
println!("Hello, world!");
This line does all the work in this little program: it prints text to the screen. There are four important details to notice here.
- Indentation: Rust style is to indent with four spaces, not a tab.
- Macros: `println!` calls a Rust macro. If it had called a function instead, it would be entered as `println` (without the `!`). For now, you just need to know that using a `!` means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions.
- String Argument: The `"Hello, world!"` string is passed as an argument to `println!`, and the string is printed to the screen.
- Semicolon: We end the line with a semicolon (`;`), which indicates that this expression is over and the next one is ready to begin. Most lines of Rust code end with a semicolon.
Compiling and Running Are Separate Steps
Before running a Rust program, you must compile it using the Rust compiler by entering the `rustc` command and passing it the name of your source file, like this:
$ rustc main.rs
After compiling successfully, Rust outputs a binary executable. You can see the executable by entering the `ls` command in your shell:
$ ls
main main.rs
This shows the source code file with the `.rs` extension, the executable file (`main.exe` on Windows, but `main` on all other platforms), and, when using Windows, a file containing debugging information with the `.pdb` extension. From here, you run the `main` or `main.exe` file, like this:
$ ./main # or .\main.exe on Windows
If your `main.rs` is your “Hello, world!” program, this line prints `Hello, world!` to your terminal.