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

标签 arrays rust unsafe

这个问题类似于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 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 .

最佳答案

您可以避免已弃用的 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 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 中的数组初始化示例docs 非常强烈地表明该警告不适用于数组。即使您不接受文档示例作为一章一节的保证,请记住该代码已经在文档中存在多年了,并且有很多代码可以使用它(我 wrote some 就在几周前和 found more )。如果保证消失,不仅一切都会崩溃,而且将无法逐个元素地初始化数组。

关于arrays - 如何创建超过 32 个泛型类型元素的数组 T : Default?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67703287/

相关文章:

javascript - 返回数组中的最大数字

php - 如何使用原始键从php数组中找到5个最大值?

arrays - 在 Rust 中将 u8 数组转换为 base64 字符串

UDP `join_multicast` 导致 OtherIOError

c# - 如何从 ASP.NET xproj 调用不安全代码

javascript - 返回 javascript 对象的特定值

c - 如何替换 2 个数组之间的值 (C)

rust - 为什么使用我的类型作为外部类型合法的参数来实现外部特征?

c# - 0 - 65535 之间第一个内存地址的空引用

c# - 基于语言的条件代码?