gpt4 book ai didi

rust - 用新类型包装 NonZeroUsize

转载 作者:行者123 更新时间:2023-12-02 16:15:43 29 4
gpt4 key购买 nike

我读过 Option<NonZeroUsize>恰好占用一个字的内存,如usize .

我想将它与 new type idiom 结合起来.我想定义 struct Pos(NonZeroUsize) , 这样编译器就不会混淆 Pos与任何其他NonZeroUsize , 但不失紧凑表示。

威尔Option<Pos>正好占用一个单词的内存?

最佳答案

默认情况下,虽然编译器可能能够优化 Option<Pos> 的大小, 没有 #[repr] 的类型注释无法保证内存布局:

The Default Representation
Nominal types without a repr attribute have the default representation. Informally, this representation is also called the rust representation.

There are no guarantees of data layout made by this representation.

但是,您可以指定 #[repr(transparent)]给力Pos具有与其单一字段相同的布局:

#[repr(transparent)]
struct Pos(NonZeroUsize);

The transparent Representation
The transparent representation can only be used on a struct or an enum with a single variant that has:

  • a single field with non-zero size, and
  • any number of fields with size 0 and alignment 1 (e.g. PhantomData).

Structs and enums with this representation have the same layout and ABI as the single non-zero sized field.

然后Option<Pos>将始终与 NonZeroUsize 具有相同的大小,根据此列表中的第 5 点和第 7 点:

Option Representation
Rust guarantees to optimize the following types T such that Option<T> has the same size as T:

  1. Box<U>
  2. &U
  3. &mut U
  4. fn, extern "C" fn
  5. num::NonZero*
  6. ptr::NonNull<U>
  7. #[repr(transparent)] struct around one of the types in this list.

关于rust - 用新类型包装 NonZeroUsize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66776552/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com