如何在 Rust 中将盒装数组转换为 Vec [英] How to convert a boxed array into a Vec in Rust

查看:103
本文介绍了如何在 Rust 中将盒装数组转换为 Vec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个装箱的结构数组,我想使用这个数组并将其插入到一个向量中.

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();

编译器错误状态

没有找到名为 into_vec 的方法,用于类型 Box<[_;4]> 在当前范围内

no method named into_vec found for type Box<[_; 4]> in the current scope

我在这里找到了类似的规范

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?

推荐答案

文档您链接到 用于切片,即[T],而您拥有的是一个长度为4 的数组:[T;4].

The documentation you link to is for slices, i.e., [T], while what you have is an array of length 4: [T; 4].

然而,您可以简单地转换它们,因为长度为 4 的数组有点是一个切片.这有效:

You can, however, simply convert those, since an array of length 4 kinda is a slice. This works:

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

这篇关于如何在 Rust 中将盒装数组转换为 Vec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆