将&[Box<[u8]>]
类型的结果转换为更容易使用的东西,例如String
或&str
的有效方法是什么?
一个示例函数是txt_data()
method from trust_dns_proto::rr:rdat::txt::TXT
。
我尝试了几项似乎无济于事的事情,例如:
fn main() {
let raw: &[Box<[u8]>] = &["Hello", " world!"]
.iter()
.map(|i| i.as_bytes().to_vec().into_boxed_slice())
.collect::<Vec<_>>();
let value = raw.iter().map(|s| String::from(*s)).join("");
assert_eq!(value, "Hello world!");
}
raw
是该类型的地方。
答案 0 :(得分:1)
解决方案似乎是这样的:
let value: String = raw
.iter()
.map(|s| String::from_utf8((*s).to_vec()).unwrap())
.collect::<Vec<String>>()
.join("");
其中密钥为from_utf8()
,(*s).to_vec()
建议使用rustc
。
答案 1 :(得分:1)
无法直接将八位字节的数组转换为str
,因为会导致数据拆分。因此String
看起来很不错。
我将str::from_utf8()
与try_fold()
结合使用:
use std::str;
fn main() {
let raw: &[Box<[u8]>] = &["Hello", " world!"]
.iter()
.map(|i| i.as_bytes().to_vec().into_boxed_slice())
.collect::<Vec<_>>();
let value = raw
.iter()
.map(|i| str::from_utf8(i))
.try_fold(String::new(), |a, i| {
i.map(|i| {
let mut a = a;
a.push_str(i);
a
})
});
assert_eq!(value.as_ref().map(|x| x.as_str()), Ok("Hello world!"));
}