Scalars - Hello, Rust!


Introduction

Rust is a statically typed programming language. This means that all values must have a known type at compile time. So how did we get away without adding annotations in our Hello, Rust example? The Rust compiler is quite excellent at type inference and will often infer types for your values and only ask you to specify a type if it can't.

Types can be scalar or compound as the programming language linguists would say. There are four primitive scalars in Rust.

Integers, Floating points, Characters and Boolean

Rust has four basic scalar types: integers, floating point numbers, characters and Boolean values. Here is an example of each of these:

fn main() {
    let is_cool: bool = true;
    let initial: char = 'S';
    let age: u64 = 30;
    let net_worth: f32 = 2.5; // In Bitcoin of course
}

A Boolean value can be annotated with the bool keyword. A char is a character value which as you can see needs to be quoted with single quotes.

Integers can have several types based on whether they are signed or not (meaning if they can have negative values or not) and the number of bits they can store. Signed integer types include i8, i16, i32, i64 and the very large i128! Unsigned types include u8, u16, u32, u64 and u128 (even larger range 😱). Floating point types include only f32 and f64.

Since most of us are using 64-bit machines these days, stick to u64, i64 and f64 unless you have a good reason.

As you would guess, of course you can do regular Math with these. You cannot do Math between integer and floating point though. Unless you cast them:

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

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

You can print these values using our friendly println! macro as well.

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

In the example above, see the empty {} in the string literal? The println! macro will construct the right expression to print with the parameters you pass in. Every {} stands for one parameter in the order they come in.

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

This is similar to template literals in JavaScript and how they let you inline values minus the inlining values (they need to be separate parameters to println!).