How to copy a fragment in Rust?

I have a fragment that I want to play. For example, if xs = [1, 2, 3], and I need to replicate it 4 times, I would end with ys = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3].

In Haskell, I would do something like this:

ys = take (4 * length xs) $ cycle xs

How can this be done similarly in Rust?

+4
source share
1 answer

Create an iterator from array c iter, then an endlessly repeating iterator c cycle, then limit it to 4 loops with take.

fn main() {
    let xs = [5,7,13];
    let ys = xs.iter()
                .cycle()
                .take(xs.len() * 4);

    for y in ys {
        println!("{}", y);
    }
}
+4
source

Source: https://habr.com/ru/post/1691335/


All Articles