rust - 将数组传递给函数 : array must have 'Sized' type

标签 rust

我已经构造了一个这样的数组:

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

最佳答案

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/

相关文章:

for-loop - 在 Rust 中的 if block 内创建一个向量。 if作用域结束后如何使用?

vector - 有效保留一系列vec元素

rust - rustc 生成的 LLVM 在使用 lli 运​​行时会给出有关 main 参数类型的错误

rust - Rust 中的递归问题

rust - 将数据移动到 Rc/Arc 是否总是将其从堆栈复制到堆?

rust - 我们可以创建自定义 Rust 运算符吗?

rust - 为什么通过提取方法进行重构会触发借用检查器错误?

rust - 如何为关联常量在 Self 上设置显式生命周期?

rust - 实现不消耗的迭代器

google-sheets - 如何使用google_sheets4条板箱构造适当的values_update调用?