将&[Box <[u8]>]转换为字符串或&str

What's an efficient way to convert a result of type &[Box<[u8]>] into something more readily consumed like String or &str?

An example function is the txt_data() method from trust_dns_proto::rr:rdat::txt::TXT.

我尝试了几项似乎无济于事的事情,例如:

fn main() {
    let raw: &[Box<[u8]>] = &[b"Hello world!"
        .iter()
        .copied()
        .collect::<Vec<_>>()
        .into_boxed_slice()];

    let _value = raw.iter().map(|s| String::from(*s)).join("");
}

Where res is of that type.

评论
  • 何必太天真
    何必太天真 回复

    看起来解决方案是这样的:

    let _value: String = raw
        .iter()
        .map(|s| String::from_utf8((*s).to_vec()).unwrap())
        .collect::<Vec<String>>()
        .join("");
    

    Where the key is from_utf8() and the (*s).to_vec() suggested by rustc.