8.1 The main
Function
Every standalone Rust program has exactly one main
function, which acts as the entry point when you run the compiled binary.
fn main() { println!("Hello from main!"); }
- Parameters: By default,
main
has no parameters. If you need command-line arguments, retrieve them usingstd::env::args()
. - Return Type: Typically,
main
returns the unit type()
. However, you can also havemain
return aResult<(), E>
to convey error information. This pairs well with the?
operator for error propagation, though it is still useful even if you do not use?
.
8.1.1 Using Command-Line Arguments
Command-line arguments are accessible through the std::env
module:
use std::env; fn main() { let args: Vec<String> = env::args().collect(); println!("Arguments: {:?}", args); }
8.1.2 Returning a Result
from main
fn main() -> Result<(), std::io::Error> { // Code that may produce an I/O error Ok(()) }
Defining main
to return a Result
lets you handle errors cleanly. You can use the ?
operator to propagate them automatically or simply return an appropriate error value as needed.