Skip to the content.

Useful types

Box<T>

Rust provides a construct called Box<T> for putting data on the heap. For example, we can wrap the million-element array in Box::new like this:

fn main() {
    let a = Box::new([0; 1_000_000]);
    let b = a;
}

Boxes provide ownership for this allocation, and drop their contents when they go out of scope. Boxes also ensure that they never allocate more than isize::MAX bytes.

Related tops:

Examples that using raw pointers:

  1. enqueue() and dequeue() methods of Queue

Slices

Slices are a special kind of reference that refer to sub-ranges of a sequence, like a string or a vector. At runtime, a slice is represented as a “fat pointe” which contains a pointer to the beginning of the range and a length of the range.

Here is what a string slice looks like: string slice.

Examples:

fn main() {
    // slice of a string - string slice
    let s = String::from("hello world");
    let slice: &str = &s[0..5];

    assert_eq!(slice, "hello");

    // slice of an array
    let mut a = [1, 2, 3, 4, 5];
    let slice = &mut a[1..3];

    slice[0] = 9;
    assert_eq!(slice, &[9, 3]);
}

String and str

(For the memory layout, please refer to string slice).

The String type is a growable, mutable, owned, UTF-8 encoded string type. It is provided by Rust’s standard library rather tha coded into the core language.

The string slice str, usually seen in its borrowed form &str, is a reference to some UTF-8 encoded string data stored elsewhere. It’s the only one string type in the core language.