Timeline
Timeline
2025-10-22
add Vec, others todo
This article introduces bit counting operations and basic sequence types in the Rust standard library, focusing on summarizing various construction methods of Vec dynamic arrays (including memory allocation mechanisms and the use of from_raw_parts safety constraints), and explains in detail common methods such as property access, element addition, deletion, modification, query, and slice expansion, along with their exception handling mechanisms.
bit manipulation
Bit Counting
| Method Name | Return Type | Description | Example Input | Example Output |
|---|---|---|---|---|
count_ones() | u32 | Count the number of1in binary | 0b1011_0001u8 | 4 |
count_zeros() | u32 | Count the number of0in binary | 0b1011_0001u8 | 4(4 zeros in 8 bits) |
leading_zeros() | u32 | CountLeading zeros(Number of zeros from the most significant bit to the first 1) | 0b0001_0000u8 | 3 |
trailing_zeros() | u32 | CountTrailing zeros(Starting from the least significant bit) | 0b0010_0000u8 | 5 |
leading_ones() | u32 | CountLeading onesNumber | 0b1110_0000u8 | 3 |
trailing_ones() | u32 | CountTrailing onesNumber | 0b0001_1111u8 | 5 |
1 | fn main() { |
Output:
1 | [zhaohang@cyberboy rust_programming]$ cargo run |
primitive-like collections
Basic sequence type, in the top-level module of the standard library, not in std::collections, in the prelude, no explicit import needed
Vec
Construction
vec![]
Using the vec macro is convenient, as it allows initializing some values during construction.
1 | macro_rules! vec { |
Examples
1 | let v = vec![1, 2, 3]; |
Vec::new()
1 | pub const fn new() -> Vec<T> |
- Constructs a new, empty Vec
. The vector will not allocate until elements are pushed onto it.
Examples
1 | let mut vec: Vec<i32> = Vec::new(); |
Vec::with_capacity()
1 | pub fn with_capacity(capacity: usize) -> Vec<T> |
Constructs a new, empty
Vec<T>with at least the specified capacity.If
capacityis zero, the vector will not allocate.For
Vec<T>whereTis a zero-sized type, there will be no allocation and the capacity will always beusize::MAX.
Panics
Panics if the new capacity exceedsisize::MAXbytes.
Examples
1 | let mut vec = Vec::with_capacity(10); |
Vec::from_raw_parts()
1 | pub unsafe fn from_raw_parts( |
Creates a
Vec<T>directly from a pointer, a length, and a capacity.This is highly unsafe, due to the number of invariants that aren’t checked:
T needs to have the same alignment as what ptr was allocated with.
ptr must have been allocated using the global allocator, such as via the alloc::alloc function
Using a C pointer is unsafe because when Vec is dropped, it calls Rust’s allocator dealloc, but this memory was allocated by C, which is unsafe.
length needs to be less than or equal to capacity
The first
lengthvalues must be properly initialized values of typeTcapacity needs to be the capacity that the pointer was allocated with
The allocated size in bytes must be no larger than
isize::MAX
1 | use std::ptr; |
using memory that was allocated else where
1 | use std::alloc::{alloc, Layout}; |
Attribute access
vec.len
1 | pub const fn len(&self) -> usize |
Returns the number of elements
vec.is_empty
1 | pub const fn is_empty(&self) -> bool |
Returns true if there are no elements, otherwise false
Access an element
Modify an element
vec.resize
1 | pub fn resize(&mut self, new_len: usize, value: T) |
Resizes the
Vecin-place so thatlenis equal tonew_len.
Examples
1 | let mut vec = vec!["hello"]; |
vec.resize_with
1 | pub fn resize_with<F>(&mut self, new_len: usize, f: F) |
Resizes the
Vecin-place so thatlenis equal tonew_len.
Examples
1 | let mut vec = vec![1, 2, 3]; |
Insert an element
vec.insert
1 | pub fn insert(&mut self, index: usize, element: T) |
Inserts an element at position
indexwithin the vector, shifting all elements after it to the right.
Panics
Panics ifindex > len.
Examples
1 | let mut vec = vec!['a', 'b', 'c']; |
vec.push
1 | pub fn push(&mut self, value: T) |
Appends an element to the back of a collection.
Panics
Panics if the new capacity exceedsisize::MAXbytes.
Examples
1 | let mut vec = vec![1, 2]; |
vec.append
1 | pub fn append(&mut self, other: &mut Vec<T, A>) |
Moves all the elements of
otherintoself, leavingotherempty.
Examples
1 | let mut vec = vec![1, 2, 3]; |
vec.extend_from_slice
1 | pub fn extend_from_slice(&mut self, other: &[T]) |
Clones and appends all elements in a slice to the
Vec.
Examples
1 | let mut vec = vec![1]; |
vec.extend_from_within
1 | pub fn extend_from_within<R>(&mut self, src: R) |
Given a range
src, clones a slice of elements in that range and appends it to the end.
srcmust be a range that can form a valid subslice of theVec.
Examples
1 | let mut characters = vec!['a', 'b', 'c', 'd', 'e']; |
vec.into_flattened
1 | pub fn into_flattened(self) -> Vec<T, A> |
Takes a
Vec<[T; N]>and flattens it into aVec<T>.
Examples
1 | let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]]; |
Remove an element
vec.pop
1 | pub fn pop(&mut self) -> Option<T> |
Removes the last element from a vector and returns it, or None if it is empty.
Examples
1 | let mut vec = vec![1, 2, 3]; |
vec.pop_if
1 | pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> |
Removes and returns the last element from a vector if the predicate returns
true, or None if the predicate returns false or the vector is empty (the predicate will not be called in that case).
Examples
1 | let mut vec = vec![1, 2, 3, 4]; |
vec.truncate
1 | pub fn truncate(&mut self, len: usize) |
Shortens the vector, keeping the first
lenelements and dropping the rest.If
lenis greater or equal to the vector’s current length, this has no effect.
Examples
1 | let mut vec = vec![1, 2, 3, 4, 5]; |
vec.drain
1 | pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘ |
drainDrains elements in the specified index range from the Vec, returning an iteratorDrain, allowing access to each removed element one by one.
RCan be any type that represents an index range, such as:0..3、2..、..5。
Examples
1 | let mut v = vec![1, 2, 3]; |
vec.remove
1 | pub fn remove(&mut self, index: usize) -> T |
Removes and returns the element at position
indexwithin the vector, shifting all elements after it to the left.
Panics
Panics ifindexis out of bounds.
Examples
1 | let mut v = vec!['a', 'b', 'c']; |
vec.swap_remove
1 | pub fn swap_remove(&mut self, index: usize) -> T |
Removes an element from the vector and returns it.
The removed element is replaced by the last element of the vector.
Examples
1 | let mut v = vec!["foo", "bar", "baz", "qux"]; |
vec.retain
1 | pub fn retain<F>(&mut self, f: F) |
Retains only the elements specified by the predicate.
Examples
1 | let mut vec = vec![1, 2, 3, 4]; |
vec.retain_mut
1 | pub fn retain_mut<F>(&mut self, f: F) |
Retains only the elements specified by the predicate, passing a mutable reference to it.
Examples
1 | let mut vec = vec![1, 2, 3, 4]; |
vec.clear
1 | pub fn clear(&mut self) |
Clears the vector, removing all values.
Note that this method has no effect on the allocated capacity of the vector.
Examples
1 | let mut v = vec![1, 2, 3]; |
vec.split_off
1 | pub fn split_off(&mut self, at: usize) -> Vec<T, A> |
Splits the collection into two at the given index.
Returns a newly allocated vector containing the elements in the range
[at, len).
Examples
1 | let mut vec = vec!['a', 'b', 'c']; |
vec.dedup
1 | pub fn dedup(&mut self) |
Removes consecutive repeated elements in the vector according to the
PartialEqtrait implementation.If the vector is sorted, this removes all duplicates.
Examples
1 | let mut vec = vec![1, 2, 2, 3, 2]; |
1 | fn main() { |
traverse
String
std::collections
VecDeque
LinkedList
HashMap
BTreeMap
BinaryHeap
Cost of Collection Operations
| get(i) | insert(i) | remove(i) | append(Vec(m)) | split_off(i) | range | append | |
|---|---|---|---|---|---|---|---|
Vec | O(1) | O(n-i)* | O(n-i) | O(m)* | O(n-i) | N/A | N/A |
VecDeque | O(1) | O(min(i, n-i))* | O(min(i, n-i)) | O(m)* | O(min(i, n-i)) | N/A | N/A |
LinkedList | O(min(i, n-i)) | O(min(i, n-i)) | O(min(i, n-i)) | O(1) | O(min(i, n-i)) | N/A | N/A |
HashMap | O(1)~ | O(1)~* | O(1)~ | N/A | N/A | N/A | N/A |
BTreeMap | O(log(n)) | O(log(n)) | O(log(n)) | N/A | N/A | O(log(n)) | O(n+m) |
Note that where ties occur, Vec is generally going to be faster than VecDeque, and VecDeque is generally going to be faster than LinkedList.
