Itertools 和带有切片索引的函数之间的 Rust 向量类型转换/接口问题

Rust vector type conversion / interface issue between Itertools and function with slice indexing

目标: 并行生成排列和索引。

尝试: 使用 Itertools 将所有排列分配给结果向量,然后使用 rayon 处理每个排列。

最小可重现代码:

use rayon::iter::ParallelIterator;
use rayon::iter::IntoParallelIterator;
use itertools::Itertools;

fn main() {
    let data: Vec<u128> = [0, 1, 2, 3, 4, 5, 6].to_vec();
    let k = 4;

    let vector = data.into_iter().permutations(k).map_into::<Vec<u128>> 
    ().collect_vec();

    (vector).into_par_iter().for_each(move |x| index_vec(x));

}

fn index_vec(i: Vec<u128>) -> () {
    let mut colour_code: String = String::from("");
    let mut index_position = 0;

    for _ in 0..4 {
        colour_code.push_str(COLOURS[i[index_position]]);
        colour_code.push(' ');
        index_position += 1;
    }
    println!("Colour code: {}", colour_code);
}

const COLOURS: [&str; 7] = [
    "red", "yellow", "blue", "green", "pink", "grey", "orange",
];

错误: 切片索引的类型为 usize 或范围为 usize

但是,如果我将所有向量更改为类型 usize,那么 Itertools 会在 map_into 方法上抛出错误:特性 From<Vec<u128>> 没有为 Vec<usize> 实现.

如何让Itertools和slice indices配合使用?

要编译发布的代码,运行您需要做的就是将 u128 转换为 usize,用于索引数组。

目前我认为这是“安全的”,因为据我所知,没有指针大小 > 128 字节的系统。但是请注意,此转换可以

所以固定代码看起来像这样:

use rayon::iter::ParallelIterator;
use rayon::iter::IntoParallelIterator;
use itertools::Itertools;

fn main() {
    let data: Vec<u128> = [0, 1, 2, 3, 4, 5, 6].to_vec();
    let k = 4;

    let vector = data.into_iter().permutations(k).map_into::<Vec<u128>> 
    ().collect_vec();

    (vector).into_par_iter().for_each(move |x| index_vec(x));

}

fn index_vec(i: Vec<u128>) -> () {
    let mut colour_code: String = String::from("");
    let mut index_position = 0;

    for _ in 0..4 {
        colour_code.push_str(COLOURS[i[index_position] as usize]);
        colour_code.push(' ');
        index_position += 1;
    }
    println!("Colour code: {}", colour_code);
}

const COLOURS: [&str; 7] = [
    "red", "yellow", "blue", "green", "pink", "grey", "orange",
];

游乐场 link 是 here