如何对大型 Vec i32 进行切片作为 &[u8]? [英] How to slice a large Vec<i32> as &[u8]?
本文介绍了如何对大型 Vec i32 进行切片作为 &[u8]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何将 Vec
转换为 &[u8]
切片.
I don't know how to convert a Vec<i32>
into a &[u8]
slice.
fn main() {
let v: Vec<i32> = vec![1; 100_000_000];
let v_bytes: &[u8] = /* ... */;
}
我想将一个大的 Vec
写入一个文件,以便我将来可以读取它.
I want to write a large Vec<i32>
to a file so I can read it back at a future time.
推荐答案
您可以使用 std::slice::from_raw_parts
:
You can use std::slice::from_raw_parts
:
let v_bytes: &[u8] = unsafe {
std::slice::from_raw_parts(
v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>(),
)
};
按照对这个答案的评论,您应该将此代码包装在一个函数中,并让返回值借用输入,以便您尽可能使用借用检查器:
Following the comments on this answer, you should wrap this code in a function and have the return value borrow the input, so that you use the borrow checker as far as possible:
fn as_u8_slice(v: &[i32]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
v.as_ptr() as *const u8,
v.len() * std::mem::size_of::<i32>(),
)
}
}
这篇关于如何对大型 Vec i32 进行切片作为 &[u8]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文