Day 4 - Types & Variables

Juan HortaJuan Horta
2 min read

Scalar types

Rust is a statically typed language, meaning the types are known at compile time. Rust can infer type, but is also possible to specify them.

Integers

Integer type (int) is a primitive type that represent integer numbers (with no decimal part). Integers are fundamentals for control flow, counting, indexing, arithmetics and more. Rust provides mani sizes for integers, also allow them to be signed or unsigned, all of them are secure (verifies overflow) and predictable.

Available integer types are:

LENGTHSIGNEDUNSIGNED
8-biti8u8
16-biti16u16
32-bit (default)i32u32
64-biti64u64
128-biti128u128
architecture-basedisizeusize

Size for the one based on architecture (isize/usize) could be 32-bit or 64-bit.

Floating-Point

Floating-points type represent number with decimals points, this type is only available on 2 sizes:

  • 32-bit: f32

  • 64-bit (default): f64

Boolean (bool)

Classical boolean type with two possible values:

  • true

  • false

Character (char)

Char is the most primitive alphabetic type, as in another languages, it represents a single character.

Those are primitive types available in Rust 🦀

Variables

To declare new variables in rust the easiest way is with following sintax:

let x = 1;

This will create a variable called “x” with type i32 and value equals to 1. As mentioned on integers section, default type for integers is i32, so if Rust infers an integer type without specifying their type, will set to i32.

If you want to declare a variable and specify its type, this is the correct sintax:

let x: i8 = 1;
let y: f32 = 3.1416;
let c: char = 'c';

Variables in Rust are not variable at all as by default they are immutable, so if you want them to vary, mutability must be set during variable declaration:

let mut x: i128 = 123;

Following code is an extended example for variables and data types:

fn main() {
    let age: i8= 30;
    let blood_type: char = 'O';
    let is_student: bool = false;
    let height: f32 = 1.75;
    println!("The value of age is: {}", age);
    println!("The value of blood type is: {}", blood_type);
    println!("Is the person a student? {}", is_student);
    println!("The value of height is: {}", height);
}

With a solid understanding of scalar types and variables, we’re now ready to explore compound types and start writing more expressive Rust code. See you on Day 5!

0
Subscribe to my newsletter

Read articles from Juan Horta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Juan Horta
Juan Horta