Using a VecDeque
When you need to insert or remove elements regularly into or from the beginning of the vector, your performance might take quite a hit, as it will force the vector to reallocate all data that comes after it. This is especially bothersome when implementing a queue. For this reason, Rust provides you with the VecDeque
.
How to do it...
- In the folder
src/bin
, create a file calledvecdeque.rs
. - Add the following code, and run it with
cargo run --bin vecdeque
:
1 use std::collections::VecDeque; 2 3 fn main() { 4 // A VecDeque is best thought of as a 5 // First-In-First-Out (FIFO) queue 6 7 // Usually, you will use it to push_back data 8 // and then remove it again with pop_front 9 let mut orders = VecDeque::new(); 10 println!("A guest ordered oysters!"); 11 orders.push_back("oysters"); 12 13 println!("A guest ordered fish and chips!"); 14 orders.push_back("fish and chips"); 15 16 let prepared = orders.pop_front(); 17 if let Some(prepared...