» Quick Introduction to Rust » 1. Basics » 1.3 Primitives

Primitives

Scalar Types

  • Signed integers: i8, i16, i32, i64, i128 and isize
  • Unsigned integers: u8, u16, u32, u64, u128 and usize
  • Floating point: f32, f64
  • char for Unicode scalar value
  • Boolean type: bool
  • Unit type: () (an empty tuple)

Compound Types

  • Arrays like [1, 2, 3, 4, 5]
  • Tuples like (true, 58)

Variables can always be type annotated.

let is_rich: bool = true;

Numbers may additionally be annotated by a suffix. If there is no type annotations, default types will be inferred.

let a_float: f64 = 1.0;
let an_int = 5i32; // `i32` is suffix

let another_float = 58.0; // defaults to `f64`

// Underscores helps with readability
println!("One million is written as {}", 1_000_000u32);

Tuples

A tuple is a collection of values of different types. Tuples are constructed using parentheses (). Functions can use tuples to return multiple values.

fn flip(pair: (f64, bool)) -> (bool, f64) {
    let (f, b) = pair;
    (b, f) // last expression(no semicolon) used as return value
}

let big_tuple = (58u32, 2u16, -2i16, 'a');
println!("First element: {}, Second element: {}", big_tuple.0, big_tuple.1);
// First element: 58, Second element: 2

Values can be extracted from the tuple by index like big_tuple.0.

Arrays and Slices

An array is a collection of objects of the same type stored in contiguous memory. Arrays are created using brackets []. Array's length is known at compile time, so its type signature is [T; length].

// Fixed-size array
let a: [i32; 5] = [1, 2, 3, 4, 5];

let b: [i32; 10] = [5; 10]; // All elements are initialized as `5`
// [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Slices are similar to arrays, but their length is not known at compile time. Slices can be used to borrow a section of an array and have the type signature &[T].

// `start_index` 1 is included
// `end_index` 3 is excluded
let c: &[i32] = &a[1..3];
println!("{:?}", c); // [2, 3]

Code Challenge

Try to modify the code provided in the editor to reverse the slice.

Loading...
> code result goes here
Prev
Next