Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. Summary of Collections in Rust has a good summary on when to each which collection in Rust.

Construct a Vector

Construct an empty vector.

[]
0

Construct an empty vector with an (initial) capacity.

[]
0

Construct a vector of predefined values.

[0, 1, 2, 30, 4, 5, 6, 7, 8, 9]
10

Construct a vector of 0’s.

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10

Construct of vector of a fixed value with a dynamic size.

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

Define a mutable vector.

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1000, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Vec is NOT Copiable

let vec2 = vec1;
           ^^^^ value moved here
println!("{:?}", vec1);
                 ^^^^ value borrowed here after move
let vec1 = vec![1, 2, 3];
    ^^^^ move occurs because `vec1` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
borrow of moved value: `vec1`
let v2 = &v1;
         ^^^ borrowed value does not live long enough
`v1` does not live long enough
let v2 = &v1;
         ^^^ borrow of `v1` occurs here
cannot move out of `v1` because it is borrowed

Vec is Clonable

[1, 2, 3]
[1, 2, 3]

Vector Slicing

A slice is a dynamically sized type representing a “view” into a sequence of elements of type T. The slice type is written as [T]. To use a slice type it generally has to be used behind a pointer, e.g., as &[T], which is a “shared slice” (often just called a “slice”). A shared slice does not own the data it points to but instead borrows it.

[0, 1, 2, 30, 4, 5, 6, 7, 8, 9]
[0, 1, 2]
[5, 6, 7, 8, 9]

Create a New Sub Vector

Create a New Sub Vector via Slicing

[5, 6, 7, 8, 9]

Create a New Sub Vector via Iterator

[6, 7, 8, 9]

Reference to Vectors

[]
()
[0, 0, 0, 0, 0]
()
[]
()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Chunks { v: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], chunk_size: 3 }
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
Ok(10)
true
10
Err(11)
11
Err(13)
Err(0)
[2, 3, 5, 8]
Ok(0)

Sort a Vector

Sort an vector using the nature order.

[1, 2, 5, 10, 15]
[1, 2, 5, 10, 15]
[15, 10, 5, 2, 1]
[15, 10, 5, 2, 1]
["a", "bb", "ccc", "dddd"]
["a", "bb", "ccc", "dddd"]
["dddd", "ccc", "bb", "a"]
["dddd", "ccc", "bb", "a"]

Return a New Sorted Copy

[1, 5, 10, 2, 15]
IntoIter([1, 2, 5, 10, 15])
[1, 2, 5, 10, 15]

Vector of Vector

[]