这个问题类似于Initialize a large, fixed-size array with non-Copy types但是对于泛型类型的数组。
我有这个结构:
struct Foo<T>([T; 99]);
如果T
工具 Default
,如何编写 Default
的实现对于 Foo<T>
?
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();
| ^^^^^^^^^^^^^^^^^^^^^^^
|
我尝试使用新的 Shiny 的 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 aFoo<T>
have the same order as aFoo<U>
even ifT
andU
have the same size and alignment.
我不确定这句话是否适用于数组,但编译器似乎也不确定。
如何在不使用已弃用的 std::mem::uninitialized()
的情况下编写此函数?请注意,我专门使用原始数组来避免分配,因此该解决方案也应该是无分配的。
为了您的方便,这里有一个 playground link .
最佳答案
您可以避免已弃用的 std::mem::uninitialized()
按照 MaybeUninit
documentation 中的配方进行操作.
如您所见,您需要从可怕的 transmute
切换到更可怕的是transmute_copy
由于(可能)compiler issue .在这种情况下 transmute_copy()
是合理的,因为你正在转化 MaybeUninit
s(不会掉落)并且你在转化后不会接触到它。
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 asT
, 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 aMaybeUninit<T>
is not necessarily the same layout [...]"
由于(除其他事项外)利基优化,文档通常对容器发出警告是正确的; Option<usize>
的大小和 Option<&u8>
即使 usize
的大小不同,和 &u8
是平等的。
MaybeUninit
中的数组初始化示例docs 非常强烈地表明该警告不适用于数组。即使您不接受文档示例作为一章一节的保证,请记住该代码已经在文档中存在多年了,并且有很多代码可以使用它(我 wrote some 就在几周前和 found more )。如果保证消失,不仅一切都会崩溃,而且将无法逐个元素地初始化数组。
关于arrays - 如何创建超过 32 个泛型类型元素的数组 T : Default?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67703287/