demo_rust_tutorial 0.1.2

An example of a rust project.
demo_rust_tutorial-0.1.2 is not a library.

Demo rust tutorial

Just a small crate containing the exemples of the documentation. The minigrep project is not included.

Scalar Types

A scalar type represents a single value. Rust has four primary scalar types: * integers

  • floating-point
  • numbers
  • booleans
  • characters.
Length Signed Unsigned
8bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64

Each signed variant can store numbers from -(2n - 1) to 2n - 1 - 1 inclusive, where n is the number of bits that variant uses. So an i8 can store numbers from -(27) to 27 - 1, which equals -128 to 127. Unsigned variants can store numbers from 0 to 2n - 1, so a u8 can store numbers from 0 to 28 - 1, which equals 0 to 255.

Compound Types

Tuple

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
}

fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;

    let six_point_four = x.1;

    let one = x.2;
}

Array type

fn main() {
    let a = [1, 2, 3, 4, 5];
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    let a = [3; 5];
}

Invalid Array Element access

use std::io;

fn main() {
    let a = [1, 2, 3, 4, 5];

    println!("Please enter an array index.");

    let mut index = String::new();

    io::stdin()
        .read_line(&mut index)
        .expect("Failed to read line");

    let index: usize = index
        .trim()
        .parse()
        .expect("Index entered was not a number");

    let element = a[index];

    println!("The value of the element at index {index} is: {element}");
}