Data Types

Rust is statically-typed (like Java), but (unlike Java) it generally infers the types. If many types are possible (like when using parse), then we have to specify the type. With that, let's discuss the various types!

Integers

Many languages have a single integer type. Not Rust! Rust has five different integer types based on the length and whether they are signed (possibly negative) or unsigned (always positive):

What should you default to? Probably i32. It's what Rust defaults to and is generally the fastest, even on 64-bit systems.

What can you enter as an integer? Any of the following options!

Floats

Floating point numbers are a bit simpler. There are only two types: f32 and f64. In this case, the Rust default is f64.

let x = 2.0; // f64
let y: f32 = 3.0; // f32

Boolean

Just like most other languages, Rust has a boolean type that has two possible values: true or false.

let t = true;
let f: bool = false;

Characters

char represents a Unicode Scalar Value, which means it can represent more than just A-z. Here's an example:

let c = 'z';
let z = 'ℤ';
let heart_eyed_cat = '😻';

Tuples

A tuple groups together any number of values with random types. Here are some examples

let tup: (i32, f64, u8) = (500, 6.4, 1); // type annotation is optional
let tup = (500, 6.4, 1);
let (x, y, z) = tup; // destructure through pattern matching
let x = tup.0 // or by getting the element at the index!
let y = tup.1
let z = tup.2

What happens if you go out of bounds?

Arrays

Arrays are similar to tuples but every element must have the same type. In Rust, once an array is created, it cannot grow or shrink. Here's an example of a common use for arrays:

let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];

Unlike tuples, you cannot easily destructure arrays via pattiern matching. But you can get the element at the index like so:

let arr = [1, 2, 3];
let one = arr[0];

Unlike the tuple out-of-bounds message, if you go out of bounds with an array, the message is very clear:

Since the index starts at zero, it must always be one less than the length. So this error message is telling us we are going one too far!

Last updated