简体   繁体   English

如何将盒装数组转换为Rust中的Vec

[英]How to convert a boxed array into a Vec in Rust

I have a boxed array of structs and I want to consume this array and insert it into a vector. 我有一个盒装数组的结构,我想使用这个数组并将其插入到一个向量中。

My current approach would be to convert the array into a vector, but the corresponding library function does not seem to work the way I expected. 我目前的方法是将数组转换为向量,但相应的库函数似乎不像我预期的那样工作。

let foo = Box::new([1, 2, 3, 4]);
let bar = foo.into_vec();

The compiler error states 编译器错误状态

no method named into_vec found for type Box<[_; 4]> 没有为Box<[_; 4]>类型找到名为into_vec方法 Box<[_; 4]> in the current scope Box<[_; 4]>在当前范围内

I've found specifications here that look like 我发现这里的规格看起来像

fn into_vec(self: Box<[T]>) -> Vec<T>
Converts self into a vector without clones or allocation.

... but I am not quite sure how to apply it. ......但我不太确定如何应用它。 Any suggestions? 有什么建议?

I think there's more cleaner way to do it. 我认为有更清洁的方法。 When you initialize foo , add type to it. 初始化foo ,请为其添加类型。 Playground 操场

fn main() {
    let foo: Box<[u32]> = Box::new([1, 2, 3, 4]);
    let bar = foo.into_vec();

    println!("{:?}", bar);
}

The documentation you link to is for slices, ie, [T] , while what you have is an array of length 4: [T; 4] 您链接到文档是针对切片,即[T] ,而您拥有的是长度为4的数组: [T; 4] [T; 4] . [T; 4]

You can, however, simply convert those, since an array of length 4 kinda is a slice. 但是,您可以简单地转换它们,因为长度为4的数组一个切片。 This works: 这有效:

let foo = Box::new([1, 2, 3, 4]);
let bar = (foo as Box<[_]>).into_vec();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM