Commit 9fb430e3 authored by Chris's avatar Chris
Browse files

[data-types] wrote code for section

parent 38932fa9
Loading
Loading
Loading
Loading
+7 −0
Original line number Diff line number Diff line
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "data-types"
version = "0.1.0"
+6 −0
Original line number Diff line number Diff line
[package]
name = "data-types"
version = "0.1.0"
edition = "2024"

[dependencies]
+49 −0
Original line number Diff line number Diff line
use std::io;

fn main() {
    let guess: u32 = "42".parse().expect("Not a number!"); // must add ": u32" or else the compiler doesn't know what type to expect
    println!("{guess}"); // :)

    // compound data type: a tuple
    // let tup: (i32, f64, u8) = (500, 6.4, 1); // this is allowed
    let tup = (500, 6.4, 1);
    let (_x, y, _z) = tup;
    println!("the value of y is {y}");

    // you can access tuple elements by using ".0", ".1", etc.
    let x: (i32, f64, u8) = (500, 6.4, 1);
    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;

    let mut x: (i32, i32) = (1, 2);
    x.0 = 0;
    x.1 += 5;

    // here's an array
    let a = [1, 2, 3, 4, 5];

    // here's another array
    let months = ["January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"];

    // here's how to explicitly define types in an array
    let b: [i32; 5] = [1, 2, 3, 4, 5];

    let threes = [3; 5]; // here's how to initialize five values with "3"
    println!("{}", threes[3]);

    // another example:
    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}");
}