Balancing things with scalars

Rust is a static programming language. This means that all values at compile time must have a known type. I explained to you in the previous post that the Rust compiler is excellent at type inference. This means that we can get away without adding type annotations to a value where the compiler can infer types and only ask for specification (like when using const) when it can't

Types can be scalar or compound. There are four primitive scalar types in Rust. They are:

  • Integers

  • Floating Points

  • Characters

  • Booleans

fn main() {
    let is_good: bool = true; //boolean
    let initial: char = 'V'; //character
    let age: u64 = 30; //integer
    let net_worth: f32 = 1.5; //floating point
}

A Boolean value is annotated with the bool , a Character value is denoted by a char value.

Integers have several type annotations based on whether they are signed or not (meaning if they have negative values or not) and the number of bits they can store. Signed integer types include i8, i16, i32, i64, and i128. Unsigned types include: u8, u16, u32, u64, u128.

Floating point types include f32 and f64. Most machines are 64-bit machines so i64, u64, and f64 are most commonly used.

Regular mathematical expressions and computations can be done with these but cannot be done between integer and floating point unless you type cast.

fn main() {
    let price = 128;
    let tax = 23.22;
    let total = f64::from(price) + tax;
}

f64::from is a function on the f64 type. The :: operator is much like the dot operator in JavaScript when it comes to types and namespaces.

we can print these values using the println! macro.

fn main() {
    let price = 128;
    let tax = 23.22;
    let total = f64::from(price) + tax;
    println!({}, total);
}

Looking at this we can see that scalars help with setting a balance to how data is defined and stored in Rust and putting the statical typing capabilities of Rust to good use. We'll start looking at built-in data structures in Rust in the next post.