8.2 The main
Function
Every Rust program must have exactly one main
function, which serves as the entry point of the program.
fn main() { // Program entry point }
- Parameters: By default, the
main
function does not take parameters. However, you can usestd::env::args
to access command-line arguments. - Return Type: The
main
function typically returns the unit type()
. You can also have it return aResult<(), E>
for error handling.
8.2.1 Using Command-Line Arguments
To access command-line arguments, you can use the std::env
module.
use std::env; fn main() { let args: Vec<String> = env::args().collect(); println!("Arguments: {:?}", args); }
8.2.2 Returning a Result
from main
fn main() -> Result<(), std::io::Error> { // Your code here Ok(()) }
- Returning a
Result
allows the use of the?
operator for error handling in themain
function.