2.2 The main Function: Entry Point of Execution

In both Rust and C, the main function serves as the entry point of the program.

2.2.1 Rust Example

fn main() {
    println!("Hello, world!");
}
  • fn declares a function.
  • main is the name of the function.
  • The function body is enclosed in {}.
  • println! is a macro that prints to the console (similar to printf in C).

2.2.2 Comparison with C

#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    return 0;
}
  • #include <stdio.h> includes the standard I/O library.
  • int main() declares the main function returning an integer.
  • printf prints to the console.
  • return 0; indicates successful execution.

Note: In Rust, the main function returns () by default (the unit type), and you don't need to specify return 0;. However, you can have main return a Result for error handling.

2.2.3 Returning a Result from main

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    // Your code here
    Ok(())
}

This allows for robust error handling in your Rust programs.