简体   繁体   中英

How do you merge two arrays of u8 and u16 elements into an array of u8 elements?

So I have an array I've just created of u8 ( a ) and a slice of u16 ( b ). How can I get an array that is the result of concatenating the elements of a with the elements of b after turning these into u8?

I've tried a lot of modifications of the following code, but there is always some error.

fn main() {
    let a: [u8; 3] = [0x01, 0x02, 0x03];
    let b: &[u16] = &[0x0405, 0x0607, 0x0809];
    let result = [a,
                  b.iter().flat_map(|s| &s.to_be_bytes()).collect()]
                 .iter().flat_map(|e| e.iter()).collect();
    assert_eq!(result, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
}

I understand the error in that piece of code but I don't know how to fix it without creating another.

Like, I can create a as a Vec<u8> so that collect() can collect into something that implements std::iter::FromIterator . But it collects into Vec<&u8> .

I also have the feeling that it should be way more simple than my example. As if I'm missing a specific function.

The following works:

fn main() {
    let a: [u8; 3] = [0x01, 0x02, 0x03];
    let b: &[u16] = &[0x0405, 0x0607, 0x0809];
    let result: Vec<u8> = a.iter().copied()
        .chain(
            b.iter()
                .flat_map(|s| std::array::IntoIter::new(s.to_be_bytes()))
        )
        .collect();
    assert_eq!(result, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
}

This uses the newly added std::array::IntoIter , which converts an array [T; N] [T; N] into an iterator of type T , as opposed to the .iter() which produces &T . This solves the issue of combining a u8 with a &u8 .

Afterwards it uses .chain to attach both iterators together, which allows us to use different types of iterators that produce the same item, as opposed to using [a, b].iter() , which requires a and b to be the same type, as opposed to simply being iterators which produce the same type.

As a.iter().copied() and b.iter().flat_map(...) aren't the same type, you must use .chain instead of an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM