如何从 &[u8] 转换为 Vec<u8>? [英] How to convert from &[u8] to Vec<u8>?
本文介绍了如何从 &[u8] 转换为 Vec<u8>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图简单地将切片转换为向量.以下代码:
I'm attempting to simply convert a slice to a vector. The following code:
let a = &[0u8];
let b: Vec<u8> = a.iter().collect();
失败并显示以下错误消息:
fails with the following error message:
3 | let b: Vec<u8> = a.iter().collect();
| ^^^^^^^ a collection of type `std::vec::Vec<u8>` cannot be built from an iterator over elements of type `&u8`
我错过了什么?
推荐答案
迭代器只返回对元素的引用(这里是 &u8
).要获得拥有的值(此处为 u8
),您可以使用 .cloned()
.
The iterator only returns references to the elements (here &u8
). To get owned values (here u8
), you can used .cloned()
.
let a: &[u8] = &[0u8];
let b: Vec<u8> = a.iter().cloned().collect();
这篇关于如何从 &[u8] 转换为 Vec<u8>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文