Reputation: 2076
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?
Upvotes: 21
Views: 13429
Reputation: 33086
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);
Upvotes: 22
Reputation: 35196
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
.
Upvotes: 11