我构建了一个这样的数组数组:
let mut my_array = [[false; WIDTH]; HEIGHT];
其中WIDTH
和HEIGHT
以前是定义的常量。
我想将整个数组传递给一个函数,并更改数组中的值,尽管不是数组的大小/长度。
我试过了:
array_func(&my_array); // (in main function)
fn array_func(arr: &mut [[bool]]) {
println!("{:?}", arr);
}
我收到错误:
the trait 'std::marker::Sized' is not implemented for '[bool]'
note: `[bool]` does not have a constant size known at compile-time
note: slice and array elements must have `Sized` type
我的数组的大小应该在编译时知道 - 我不能改变数组的大小。至少,我认为let mut my_array
意味着我可以更改数组中的值,但不能更改数组的大小。
答案 0 :(得分:6)
the trait 'std::marker::Sized' is not implemented for '[bool]'
Rust中基本上有两种形式的数组:
[T; N]
是一个N
T
的数组,它是Sized
。[T]
是一个T
大小的数组,仅在运行时已知,它不是Sized
,只能真正被操作为切片(&[T]
)。您的代码中存在的问题是,在[[bool]]
中,内部[bool]
因此不是Sized
,并且只有Sized
个元素可以存储在数组中。
最简单的解决方案可能是更新函数签名以正确注释数组大小:
fn array_func(arr: &mut [[bool; WIDTH]; HEIGHT]) {
}
可以将&[T; N]
强制转换为&[T]
,因此您也可以使用:
fn array_func(arr: &mut [[bool; WIDTH]]) {
}
但是,无法将[[T; N]]
强制转换为[&[T]]
,因此无法将&[[T; N]; M]
强制转换为&[&[T]; M]
(因此{{1}因为数组和对数组的引用具有不同的内存表示,因此这将是一个O(M)操作(并且需要一个大小为&[&[T]]
的新数组)。
至少,我认为
M
意味着我可以更改数组中的值,但不能更改数组的大小。
这是正确的,数组的维度是其类型的一部分,而let mut my_array
只允许更改值而不是类型。