Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a VecDeque from a vector?

Tags:

vector

rust

I am trying to quickly create a VecDeque using the ::from(). I have the following Rust code:

use std::collections::VecDeque;

fn main() {
    let ring = VecDeque::from([1, 2, 3]);
    println!("{:?}", ring);
}

I get the following compiler error:

error[E0277]: the trait bound `std::collections::VecDeque<_>: std::convert::From<[{integer}; 3]>` is not satisfied
 --> src/main.rs:4:16
  |
4 |     let ring = VecDeque::from([1, 2, 3]);
  |                ^^^^^^^^^^^^^^ the trait `std::convert::From<[{integer}; 3]>` is not implemented for `std::collections::VecDeque<_>`
  |
  = help: the following implementations were found:
            <std::collections::VecDeque<T> as std::convert::From<std::vec::Vec<T>>>
  = note: required by `std::convert::From::from`

This looks like the VecDeque collection doesn't implement the from trait, but the docs suggest that it does. What am I doing wrong?

like image 372
Simon Brahan Avatar asked Feb 23 '18 13:02

Simon Brahan


People also ask

How do you make an empty vector in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new(); This call constructs a new, empty Vec<T> .

What is Vecdeque?

A double-ended queue implemented with a growable ring buffer. The “default” usage of this type as a queue is to use push_back to add to the queue, and pop_front to remove from the queue.

Are vectors contiguous rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents.

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.


2 Answers

use std::collections::VecDeque;
use std::iter::FromIterator;
fn main() {
    let ring = VecDeque::from_iter(&[1, 2, 3]);
    println!("{:?}", ring);
}

It only implements From<Vec<T>> and [...] isn't a Vec. Since it implements FromIterator, you can use any kind of iterator as a source with from_iter. &[1, 2, 3] is because from_iter takes an Iterator.

like image 107
Doug Avatar answered Oct 22 '22 05:10

Doug


Alternatively, you can also use From<Vec<T>>:

fn from(other: Vec<T>) -> VecDeque<T>

Turn a Vec<T> into a VecDeque<T>.

This avoids reallocating where possible, but the conditions for that are strict, and subject to change, and so shouldn't be relied upon unless the Vec<T> came from From<VecDeque<T>> and hasn't been reallocated.

Example:

let vector: Vec<i32> = vec![0, 1, 2];
let vec_queue: VecDeque<i32> = VecDeque::from(vector);
like image 26
Yuchen Avatar answered Oct 22 '22 06:10

Yuchen