rust函数从嵌套迭代器中返回

ohfgkhjo  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个函数,它可以从一个9乘9的数字网格中创建一个数独网格,如果发现一个无效的数字,它应该返回该数字的位置信息(其功能在注解掉的代码中)。代码当前运行,但如果注解掉的代码用于替换.unwrap(),则编译器会抛出一系列错误,(如果我的解释正确的话)显示return返回的值是std::array::from_fn而不是unsolved_sudoku_from_nums。我如何修复这个问题以使其按预期工作?谢谢,

/// parse nums into an UnsovedSudoku, 1-9 will be parsed as values 1-9, 0 will be parsed as an unsolved cell and all
///  other values will cause the function to return an InvalidInt error.
fn unsolved_sudoku_from_nums(nums: &[[u8; 9]; 9]) -> Result<UnsolvedSudoku, InvalidInt> {
    Ok(UnsolvedSudoku (
        std::array::from_fn(|i|{
            std::array::from_fn(|j| {
                match nums[i][j] {
                    0 => WorkingCell::PossibleValues([true; 9]),
                    int => WorkingCell::Solved(
                        SudokuValue::from_int(int)
                            .unwrap()
                            // .expect(
                            //     return Err(InvalidInt{
                            //         row: i, 
                            //         column: j, 
                            //         int: nums[i][j],
                            //     })
                            // )
                        ),
                }
            })
        })
    ))
}

字符串
FYI

struct UnsolvedSudoku (
    [[WorkingCell; 9]; 9]
);

2nc8po8w

2nc8po8w1#

如果数组中的元素类型实现了Default,则可以编写一个非常简单的不稳定标准库函数std::array::try_from_fn()的实现它的优化程度不如try_from_fn,但不需要不安全的代码:

fn array_try_from_fn<const N: usize, T, E, F>(mut f: F) -> Result<[T; N], E>
where
    T: Default,
    F: FnMut(usize) -> Result<T, E>,
{
    let mut arr = std::array::from_fn(|_| T::default());

    for i in 0..N {
        arr[i] = f(i)?;
    }

    Ok(arr)
}

字符串
这为您提供了标准库函数的人体工程学,并允许您在try_from_fn稳定时轻松地交换此函数。

相关问题