编辑:自 Rust 版本>= 1.47 开始,此问题不再相关,因为已经开始实施 "const generics"。
我正在尝试用 Rust 实现数独求解器以进行学习。 我正在尝试创建一个由固定大小(81)的Cell
数组(其中Cell
是Copy
)组成的棋盘,但似乎无法使其正常工作。 我可以创建一个包含9个Cell
的线路,所以我想我遇到了这种转换类型的问题,对于这种转换,只有32个TryFrom
泛型可用。
目前,Cell
看起来像这样:
#[derive(Debug, Default, Clone, Copy)]
struct Cell {
row: u8,
column: u8,
}
这是有效的:
use std::convert::TryInto;
fn main() {
let cells: Vec<Cell> = std::iter::repeat(0)
.zip(0..9u8)
.map(|(row, column)| Cell { row, column} )
.collect();
let c: Box<[Cell; 9]> = cells.into_boxed_slice().try_into().unwrap();
println!("{:#?}", c);
}
但是这个不行:
use std::convert::TryInto;
fn main() {
let cells: Vec<Cell> = (0..9u8).into_iter()
.flat_map(|x| {
std::iter::repeat(x)
.zip(0..9u8)
})
.map(|(row, column)| Cell { row, column} )
.collect();
let c: Box<[Cell; 81]> = cells.into_boxed_slice().try_into().unwrap();
println!("{:#?}", c);
}
我尝试像这样使用来自std
的代码作为指南:
impl TryFrom<Box<[Cell]>> for Box<[Cell; 81]> {
type Error = Box<[Cell]>;
fn try_from(boxed_slice: Box<[Cell]>) -> Result<Self, Self::Error> {
if boxed_slice.len() == 81 {
Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [Cell; 91]) })
} else {
Err(boxed_slice)
}
}
}
但是这会遇到一个关于 trait 冲突实现
的错误,我想这很合理。
我知道我可以简单地使用一个 Vec
或者做一些像 [[Cell; 9]; 9]
这样的事情,但我真的想了解发生了什么。在尝试弄清楚这个问题的过程中,我看到了许多类似的问题,人们试图使用没有实现 Copy
的类型,那就是问题所在,但在这里并非如此,我无法弄清楚如何让它工作。
try_into()
),第二个示例也存在问题,尝试从迭代器构建[Cell; 81]
,第三个带有impl
的块中有91
而不是81
等。 - Acorn