正确的方式来访问Vec <&[u8]>作为字符串

时间:2019-06-19 09:15:04

标签: string utf-8 rust slice

我有一个Vec<&[u8]>,我想像这样转换为String

let rfrce: Vec<&[u8]> = rec.alleles();

for r in rfrce {
    // create new String from rfrce
}

我尝试了此操作,但由于只能将u8转换为char,而不能将[u8]转换为char,因此无法正常工作

let rfrce = rec.alleles();

let mut str = String::from("");

for r in rfrce {
    str.push(*r as char);
}

2 个答案:

答案 0 :(得分:4)

由于ru8的数组,因此需要将其转换为有效的&str并使用push_str的{​​{1}}方法。

String

Rust Playground

答案 1 :(得分:1)

我会选择TryFrom<u32>

fn to_string(v: &[&[u8]]) -> Result<String, std::char::CharTryFromError> {
    /// Transform a &[u8] to an UTF-8 codepoint
    fn su8_to_u32(s: &[u8]) -> Option<u32> {
        if s.len() > 4 {
            None
        } else {
            let shift = (0..=32).step_by(8);
            let result = s.iter().rev().cloned().zip(shift).map(|(u, shift)| (u as u32) << shift).sum();
            Some(result)
        }
    }

    use std::convert::TryFrom;

    v.iter().map(|&s| su8_to_u32(s)).try_fold(String::new(), |mut s, u| {
        let u = u.unwrap(); //TODO error handling
        s.push(char::try_from(u)?);
        Ok(s)
    })
}

fn main() {
    let rfrce: Vec<&[u8]> = vec![&[48][..], &[49][..], &[50][..], &[51][..]];
    assert_eq!(to_string(&rfrce), Ok("0123".into()));

    let rfrce: Vec<&[u8]> = vec![&[0xc3, 0xa9][..]]; // https://www.utf8icons.com/character/50089/utf-8-character
    assert_eq!(to_string(&rfrce), Ok("쎩".into()));

}