标签: list rust replicate
我有一个我要复制的切片。例如,如果xs = [1, 2, 3],我需要复制4次,我最终会得到ys = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]。
xs = [1, 2, 3]
ys = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
在Haskell中,我会做这样的事情:
ys = take (4 * length xs) $ cycle xs
在Rust中如何做到这一点?
答案 0 :(得分:4)
使用iter从数组创建一个迭代器,然后使用cycle创建一个无休止重复的迭代器,然后使用take将其限制为4个周期。
iter
cycle
take
fn main() { let xs = [5,7,13]; let ys = xs.iter() .cycle() .take(xs.len() * 4); for y in ys { println!("{}", y); } }