2017-07-01 36 views
2

我已经构造数组的数组这样的:传递数组函数:阵列必须具有“尺寸”型

let mut my_array = [[false; WIDTH]; HEIGHT]; 

其中WIDTHHEIGHT预先定义的常量。

我想将整个数组传递给一个函数,并更改数组中的值,但不是数组的大小/长度。

我已经试过:

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意味着我可以更改数组中的值,但不是数组的大小。

回答

6
the trait 'std::marker::Sized' is not implemented for '[bool]' 

基本上有2种形式的阵列中锈:

  • [T; N]NT秒的阵列,它是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只允许改变值不是类型。

相关问题