如何通过适配器在一行中重复或连续两次切片?

问题描述 投票:0回答:1

我可以使用iter适配器做同样的工作吗?

fn mutiply_bytes(buf_in: &[u8], mul: usize) -> Vec<u8> {
    let length = buf_in.len() * mul;
    let mut buf_out = Vec::with_capacity(length);
    for i in 0..length{
        buf_out.push(buf_in[i%buf_in.len()]);
    }
    buf_out
}
rust
1个回答
1
投票

std::iter::repeat可能会有所帮助

fn mutiply_bytes(buf_in: &[u8], mul: usize) -> Vec<u8> {
    std::iter::repeat(buf_in)
        .take(mul)
        .flatten()
        .cloned()
        .collect::<Vec<u8>>()
}
© www.soinside.com 2019 - 2024. All rights reserved.