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?
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> .
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.
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.
A contiguous growable array type, written as Vec<T> , short for 'vector'.
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
.
Alternatively, you can also use From<Vec<T>>
:
fn from(other: Vec<T>) -> VecDeque<T>
Turn a
Vec<T>
into aVecDeque<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 fromFrom<VecDeque<T>>
and hasn't been reallocated.
Example:
let vector: Vec<i32> = vec![0, 1, 2];
let vec_queue: VecDeque<i32> = VecDeque::from(vector);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With