Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_0000
Byte (u8 only)b'A'


Floating-Point Types

Rust’s floating-point types are f32 and f64, which are 32 bits and 64 bits in size, respectively. The default type is f64 because on modern CPUs, it’s roughly the same speed as f32 but is capable of more precision. All floating-point types are signed.


Code Block
fn main() {
    let x = 2.0; // f64

    let y: f32 = 3.0; // f32
}


Boolean Type

Booleans are one byte in size. The Boolean type in Rust is specified using bool.

Code Block
fn main() {
    let t = true;

    let f: bool = false; // with explicit type annotation
}


Character Type

Rust’s char type is the language’s most primitive alphabetic type.

Note that we specify char literals with single quotes, as opposed to string literals, which use double quotes.

Code Block
fn main() {
    let c = 'z';
    let z: char = 'ℤ'; // with explicit type annotation
    let heart_eyed_cat = '😻';
}


Compound Types

Compound types can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

Tuple Type

A tuple is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size.


Code Block
fn main() {
    let tup = (500, 6.4, 1);
    let (x, y, z) = tup;
    println!("The value of y is: {y}");
}

This program first creates a tuple and binds it to the variable tup. It then uses a pattern with let to take tup and turn it into three separate variables, x, y, and z. This is called destructuring because it breaks the single tuple into three parts. Finally, the program prints the value of y, which is 6.4.


We can also access a tuple element directly by using a period (.) followed by the index of the value we want to access. For example:

Code Block
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);
    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;
}


Array Type

Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length.

Code Block
fn main() {
	let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];

	let a: [i32; 5] = [1, 2, 3, 4, 5];

	//access values

	let first = a[0];
	let second = a[1];
}



IntelliJ IDE

To use Rust in IntelliJ install the following plugins:

...