VecDeque : as_slices() not working as expected?

⚓ rust    📅 2025-05-18    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

I'm new to Rust and still learning. While experimenting with VecDeque, I noticed a rather inconsistent (I believe) output from as_slices(). Below is my code:

fn main() {
    let mut deq = VecDeque::from([1, 2, 3]);
    
    deq.push_back(4);
    deq.push_back(5);
    deq.push_front(10);
    deq.push_front(9);
    
    println!("(front, back) = {:?}", deq.as_slices());
    
    while let Some(_front) = deq.pop_front() {
    }
    
    deq.push_back(1);
    deq.push_back(20);
    println!("(front, back) = {:?}", deq.as_slices());
    
    deq.push_front(10);
    deq.push_front(100);
    println!("(front, back) = {:?}", deq.as_slices());
    
}

The first time as_slices() was called, the output was as expected -

(front, back) = ([9, 10], [1, 2, 3, 4, 5]) // two slices with values from front and back respectively.

However, after using pop_front() to pop all values from deq, the subsequent push_back and push_front is always yielding one slice with all the values from deq and one empty slice.

(front, back) = ([1, 20], [])
(front, back) = ([100, 10, 1, 20], [])

Although the insertions happened as expected, the slices are different than before where I saw front and back values in separate slices.

Is this an expected behavior and why is this happening?

Code link : Rust Playground

Thank you!

2 posts - 2 participants

Read full topic

🏷️ rust_feed