如何创建一个包含超过 32 个元素的泛型类型 T: Default 的数组?

How to create an array of more than 32 elements of a generic type T: Default?

此问题与 Initialize a large, fixed-size array with non-Copy types 类似,但针对的是泛型数组。

我有这个结构:

struct Foo<T>([T; 99]);

如果 T 实现 Default,我如何为 Foo<T> 编写 Default 的实现?

impl<T: Default> Default for Foo<T> {
    fn default() -> Self {
        // ???
    }
}

天真的方法不起作用,因为 Default 仅适用于长度不超过 32 的数组:

Foo(Default::default())
error[E0277]: the trait bound `[_; 99]: Default` is not satisfied
 --> src/lib.rs:5:13
  |
5 |         Foo(Default::default())
  |             ^^^^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `[_; 99]`
  |

这有效(改编自 here),但使用了一个已弃用的函数:

Foo(unsafe {
    let mut arr: [T; 99] = std::mem::uninitialized();
    for e in &mut arr {
        std::ptr::write(e, T::default());
    }
    arr
})
warning: use of deprecated function `std::mem::uninitialized`: use `mem::MaybeUninit` instead
 --> src/lib.rs:6:36
  |
6 |             let mut arr: [T; 99] = std::mem::uninitialized();
  |                                    ^^^^^^^^^^^^^^^^^^^^^^^
  |

我尝试使用新的闪亮的 MaybeUninit,遵循 an example in its docs:

Foo(unsafe {
    use std::mem::MaybeUninit;
    let mut arr: [MaybeUninit<T>; 99] = {
        MaybeUninit::uninit().assume_init()
    };
    for e in &mut arr {
        *e = MaybeUninit::new(T::default());
    }
    std::mem::transmute(arr)
})
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
  --> src/lib.rs:13:13
   |
13 |             std::mem::transmute(arr)
   |             ^^^^^^^^^^^^^^^^^^^
   |
   = note: source type: `[MaybeUninit<T>; 99]` (size can vary because of T)
   = note: target type: `[T; 99]` (size can vary because of T)

保证 MaybeUninit<T> 的大小与 T 相同,但这并不一定意味着 [MaybeUninit<T>; 99][T; 99] 的大小相同,根据文档:

However remember that a type containing a MaybeUninit<T> is not necessarily the same layout; Rust does not in general guarantee that the fields of a Foo<T> have the same order as a Foo<U> even if T and U have the same size and alignment.

我不确定这句话是否适用于数组,但编译器似乎也不确定。

如何在不使用已弃用的 std::mem::uninitialized() 的情况下编写此函数?请注意,我专门使用原始数组来避免分配,因此解决方案也应该是无分配的。

为方便起见,这里有一个playground link

您可以按照 MaybeUninit documentation 中的方法避免已弃用的 std::mem::uninitialized() 函数。

正如您发现的那样,由于(很可能)compiler issue,您需要从可怕的 transmute 切换到更可怕的 transmute_copy。在这种情况下,transmute_copy() 是合理的,因为你正在转化 MaybeUninits(它们没有被丢弃)并且在转化之后你没有接触它。

impl<T: Default> Default for Foo<T> {
    fn default() -> Self {
        Foo(unsafe {
            // `assume_init` is sound here because the type we are claiming to have
            // initialized consists of `MaybeUninit`s, which do not require initialization.
            let mut arr: [MaybeUninit<T>; 99] = MaybeUninit::uninit().assume_init();
            for e in &mut arr {
                *e = MaybeUninit::new(T::default());
            }
            // transmute_copy required due to a (likely) compiler bug,
            // see https://github.com/rust-lang/rust/issues/62875
            std::mem::transmute_copy(&arr)
        })
    }
}

It's guaranteed that MaybeUninit<T> has the same size as T, but that doesn't necessarily mean that the same holds for [MaybeUninit<T>; 99] and [T; 99], as per the docs: "However remember that a type containing a MaybeUninit<T> is not necessarily the same layout [...]"

由于(除其他事项外)利基优化,文档警告一般容器是正确的; Option<usize>Option<&u8> 的大小不同,即使 usize&u8 的大小相同。

MaybeUninit 文档中的数组初始化示例非常有力地表明该警告不适用于数组。即使您不接受文档示例作为章节和章节保证,请记住该代码已经在文档中存在多年,并且有很多使用它的代码 (I wrote some just a couple of weeks ago and found more)。如果保证消失,不仅一切都会崩溃,而且无法逐个元素地初始化数组。