将数组传递给函数:数组必须具有“大小"类型 [英] Passing array to function: array must have 'Sized' type

查看:57
本文介绍了将数组传递给函数:数组必须具有“大小"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've constructed an array of arrays like this:

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

其中 WIDTHHEIGHT 是之前定义的常量.

where WIDTH and HEIGHT are previously defined constants.

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

I want to pass the whole array to a function, and change the values within the array, although not the size/length of the array.

我试过了:

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 size of my array should be known at compile time - I can't change the size of an array. 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.

推荐答案

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

Rust 中基本上有两种形式的数组:

There are essentially 2 forms of arrays in Rust:

  • [T;N]是一个N T的数组,它是Sized.
  • [T] 是一个 T 的数组,其大小仅在运行时已知,它不是 Sized,并且只能真正作为切片操作(&[T]).
  • [T; N] is an array of N Ts, it is Sized.
  • [T] is an array of T of size only known at run-time, it is NOT Sized, and can only really be manipulated as a slice (&[T]).

您在代码中遇到的问题是,在 [[bool]] 中,内部 [bool] 因此不是 Sized,并且只有 Sized 元素可以存储在数组中.

The problem you have in your code is that in [[bool]], the inner [bool] is therefore NOT Sized, and only Sized elements can be stored in an array.

最简单的解决方案可能是更新您的函数签名以正确注释数组大小:

The simplest solution is probably to update your function signature to correctly annotate the array sizes:

fn array_func(arr: &mut [[bool; WIDTH]; HEIGHT]) {
}

可以强制一个 &[T;N]&[T],所以你也可以使用:

It is possible to coerce a &[T; N] to a &[T], so you could also use:

fn array_func(arr: &mut [[bool; WIDTH]]) {
}

然而,不能强制一个 [[T;N]][&[T]],因此,不可能强制一个 &[[T;否];M] 变成 &[&[T];M](因此是 &[&[T]]),因为数组和对数组的引用具有不同的内存表示,因此这将是 O(M) 操作(并且需要一个大小为 M 的新数组).

However, it is NOT possible to coerce a [[T; N]] to [&[T]], and thus, not possible to coerce a &[[T; N]; M] into a &[&[T]; M] (and thus &[&[T]]), because an array and a reference to an array have a different memory representation and thus this would be an O(M) operation (and require a new array of size M).

至少,我认为 let mut my_array 意味着我可以更改数组中的值,但不能更改数组的大小.

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 只允许更改值而不是类型.

This is correct indeed, the dimensions of the array are part of its type, and mut only allows changing the value not the type.

这篇关于将数组传递给函数:数组必须具有“大小"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆