我有一个从文件中读取的Vec<u8>
字节序列 - 这些字节是文本格式(可能是UTF-16或其他一些2个字节的奇怪格式),我想将其转换为UTF-8。
let title = Vec::from_iter(bytes.take(title_length));
// Some Vec<u8> to &[u16] magic
let title = String::from_utf16_lossy(title);
目前我使用的是相当糟糕的代码:
let title: &[u16] = unsafe { std::slice::from_raw_parts(title_data.as_ptr(), title_data.len()) };
虽然这应该可以工作,但我遇到了错误,可能是由于take()
调用造成的:
error: mismatched types:
expected `*const u16`,
found `*const core::result::Result<u8, std::io::error::Error>`
(expected u16,
found enum `core::result::Result`) [E0308]
我是否应该映射take
迭代器或其他内容?
title_data
,但是它在任何地方都没有定义。最好提供能够在Rust Playground上重现错误的代码。 - Shepmaster