2.3 The main
Function: Program Entry Point
As in C, a Rust program starts executing in the main
function, typically found in a file named main.rs
. Larger projects can have multiple .rs
files and libraries, all compiled under one “crate.”
2.3.1 A Simple Rust Program
fn main() { println!("Hello, world!"); }
fn
declares a function.main
is the entry point of a Rust program.- A function’s name is followed by a parameter list in parentheses.
println!
is a macro (not a function) that prints to standard output.- Function bodies and code blocks are enclosed in
{}
. - Statements typically end with a semicolon.
- Expressions, such as
a > b
or code blocks, do not require a semicolon.
2.3.2 Comparison with C
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
- C’s
main
returns an integer, usually0
upon success. - Rust’s
main
returns()
, the unit type, by default.