我已经构造了一个这样的数组:
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
意味着我可以更改数组中的值,但不能更改数组的大小。
最佳答案
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]
(因此 &[&[T]]
),因为数组和对数组的引用具有不同的内存表示,因此这将是一个 O(M) 操作(并且需要一个大小为 M
的新数组)。
At least, I thought the
let mut my_array
meant I could change the values within the array but not the size of the array.
这确实是正确的,数组的维度是其类型的一部分,mut
只允许更改值而不是类型。
关于rust - 将数组传递给函数 : array must have 'Sized' type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864442/