Skip to content

Data types in Rust

Before we write any more code, let’s quickly discuss variables so we can understand some rust concepts before we get into the meat of the code

You can define variables using the let keyword (very similar to JS)

You can assign the type of the variable, or it can be inferred as well.

1. Numbers

fn main() {
let x: i32 = 1;
println!("{}", x);
}
  • Equivalent typescript code

    function main() {
    let x: number = 1;
    console.log(x);
    }
    main()
  • What happens if we overflow?

    fn main() {
    let mut num: i8 = 124;
    for i in 0..100 {
    num += 127;
    }
    print!("Number: {}", num)
    }

2. Booleans

Bools can have two states, true or false

fn main() {
let is_male = false;
let is_above_18 = true;
if is_male {
println!("You are a male");
} else {
println!("You are not a male");
}
if is_male && is_above_18 {
print!("You are a legal male");
}
}
  • Equivalent typescript code

    function main() {
    let is_male = false;
    let is_above_18 = true;
    if (is_male) {
    console.log("You are a male");
    } else {
    console.log("You are not a male");
    }
    if (is_male && is_above_18) {
    console.log("You are a legal male");
    }
    }
    main();

3. Strings

There are two ways of doing strings in rust. We’ll be focussing on the easier one

fn main() {
let greeting = String::from("hello world");
println!("{}", greeting);
}
  • Equivalent typescript code

    function main() {
    let greeting = "hello world";
    console.log(greeting);
    // console.log(greeting[1000]);
    }

4. Arrays

fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];
println!("{}", arr.len());
}

5. Vectors

fn main() {
let mut xs = vec![1, 2, 3];
print!("{}", xs.len());
xs.push(4);
print!("{}", xs.len());
}