2.3 The main Function: The Entry Point
Execution of a Rust binary begins at the main function, just like in C. By convention, this function often resides in a file named src/main.rs within a Cargo project. A project can contain multiple .rs files organized into modules and potentially link against library crates.
2.3.1 A Minimal Rust Program
fn main() { println!("Hello, world!"); }
fn: Keyword to declare a function.main: The special name for the program’s entry point.(): Parentheses enclose the function’s parameter list (empty in this case).{}: Curly braces enclose the function’s body.println!: A macro (indicated by the!) for printing text to the standard output, followed by a newline.;: Semicolons terminate most statements.- Rust follows indentation conventions similar to those in C, but—as in C—this indentation is purely for readability and has no effect on the compiler.
2.3.2 Comparison with C
#include <stdio.h>
int main(void) { // Or int main(int argc, char *argv[])
printf("Hello, world!\n");
return 0; // Return 0 to indicate success
}
- C’s
maintypically returns anintstatus code (0 for success). - Rust’s
mainfunction, by default, returns the unit type(), implicitly indicating success. It can be declared to return aResulttype for more explicit error handling, as we’ll see later.