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

问题描述

目标:并行生成排列并索引到每个排列中。

尝试:使用 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 和切片索引协同工作?

解决方法

要使发布的代码编译并运行,您只需将 u128 转换为用于索引数组的 usize

我目前认为这是“安全的”,因为我知道没有指针大小 > 128 字节的系统。但是请注意,这种转换可能fail in theory

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

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",];

游乐场链接是 here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...