如何从矢量创建VecDeque?

时间:2018-02-23 13:21:13

标签: vector rust

我正在尝试使用VecDeque快速创建::from()。我有以下Rust代码:

use std::collections::VecDeque;

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

我收到以下编译错误:

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`

这似乎VecDeque集合未实现from特征,但the docs表示确实如此。我做错了什么?

2 个答案:

答案 0 :(得分:4)

std::string

它只实现use std::collections::VecDeque; use std::iter::FromIterator; fn main() { let ring = VecDeque::from_iter(&[1, 2, 3]); println!("{:?}", ring); } From<Vec<T>>不是[...]。由于它实现了Vec,因此您可以使用任何类型的迭代器作为FromIterator的源。 from_iter是因为&[1, 2, 3]需要from_iter

答案 1 :(得分:2)

或者,您也可以使用From<Vec<T>>

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

Vec<T>变成VecDeque<T>

     

这避免了在可能的情况下进行重新分配,但是这样做的条件是严格的,并且会随时更改,因此除非Vec<T>来自From<VecDeque<T>>并且没有重新分配,否则不应依赖它

示例:

let vector: Vec<i32> = vec![0, 1, 2];
let vec_queue: VecDeque<i32> = VecDeque::from(vector);