Rust by example - Getting Started

less than 1 minute read


Rust by example

Getting Started

By Example

/* rust intro
*/
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

/// This is the main function outer doc
fn main() {
    //! This is the main function inner doc
    // use snake_case and 4 spaces for indentation

    // my_seconds is immutable
    let my_seconds = THREE_HOURS_IN_SECONDS;
    let mut bananas = 5; // mutable
    bananas = bananas + 1; // can be changed
    println!("The value of bananas is: {bananas}");

    let y = { //
        let x = 3; // statement
        x + 1 // no semicolon
    }; // expression
    // x is not valid ouside the scope
    println!("The value of y is: {y}");

    { // new scope
        let my_seconds = my_seconds + 1; // shadowing the previous value
        println!("The value of my_seconds in the inner scope is: {my_seconds}");
    }
    println!("The value of my_seconds is: {my_seconds}");
}
$ rustc intro.rs
$ ./intro
The value of bananas is: 6
The value of y is: 4
The value of my_seconds in the inner scope is: 10801
The value of my_seconds is: 10800

This code will be explained in the following sections.

Updated:

Leave a Comment