当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust size_of用法及代码示例


本文简要介绍rust语言中 Function std::mem::size_of 的用法。

用法

pub const fn size_of<T>() -> usize

返回类型的大小(以字节为单位)。

更具体地说,这是数组中具有该项目类型的连续元素之间的字节偏移量,包括对齐填充。因此,对于任何类型 T 和长度 n[T; n] 的大小为 n * size_of::<T>()

一般来说,一个类型的大小在编译过程中是不稳定的,但特定类型(如原语)是稳定的。

下表给出了基元的大小。

类型size_of::<类型>()
()0
bool1
u81
u162
u324
u648
u12816
i81
i162
i324
i648
i12816
f324
f648
char4

此外,usizeisize具有相同的大小。

*const T&TBox<T>Option<&T>Option<Box<T>> 类型都具有相同的大小。如果 T 是 Sized,则所有这些类型的大小都与 usize 相同。

指针的可变性不会改变它的大小。因此,&T&mut T 具有相同的大小。对于 *const T*mut T 也是如此。

#[repr(C)] 项目的大小

项目的C 表示具有定义的布局。使用这种布局,项目的大小也是稳定的,只要所有字段都有一个稳定的大小。

结构的大小

对于 structs ,大小由以下算法确定。

对于按声明顺序排序的结构中的每个字段:

  1. 添加字段的大小。
  2. 将当前大小向上舍入到下一个字段的 alignment 最接近的倍数。

最后,将结构体的大小舍入为其 alignment 最接近的倍数。结构体的对齐方式通常是其所有字段中最大的对齐方式;这可以通过使用 repr(align(N)) 进行更改。

C 不同,零大小的结构不会四舍五入到一个字节的大小。

枚举的大小

除了判别式之外不携带任何数据的枚举与编译它们的平台上的 C 枚举具有相同的大小。

工会规模

联合的大小是其最大字段的大小。

C 不同,零大小的联合不会四舍五入到一个字节的大小。

例子

use std::mem;

// Some primitives
assert_eq!(4, mem::size_of::<i32>());
assert_eq!(8, mem::size_of::<f64>());
assert_eq!(0, mem::size_of::<()>());

// Some arrays
assert_eq!(8, mem::size_of::<[i32; 2]>());
assert_eq!(12, mem::size_of::<[i32; 3]>());
assert_eq!(0, mem::size_of::<[i32; 0]>());


// Pointer size equality
assert_eq!(mem::size_of::<&i32>(), mem::size_of::<*const i32>());
assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Box<i32>>());
assert_eq!(mem::size_of::<&i32>(), mem::size_of::<Option<&i32>>());
assert_eq!(mem::size_of::<Box<i32>>(), mem::size_of::<Option<Box<i32>>>());

使用 #[repr(C)]

use std::mem;

#[repr(C)]
struct FieldStruct {
    first: u8,
    second: u16,
    third: u8
}

// The size of the first field is 1, so add 1 to the size. Size is 1.
// The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
// The size of the second field is 2, so add 2 to the size. Size is 4.
// The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
// The size of the third field is 1, so add 1 to the size. Size is 5.
// Finally, the alignment of the struct is 2 (because the largest alignment amongst its
// fields is 2), so add 1 to the size for padding. Size is 6.
assert_eq!(6, mem::size_of::<FieldStruct>());

#[repr(C)]
struct TupleStruct(u8, u16, u8);

// Tuple structs follow the same rules.
assert_eq!(6, mem::size_of::<TupleStruct>());

// Note that reordering the fields can lower the size. We can remove both padding bytes
// by putting `third` before `second`.
#[repr(C)]
struct FieldStructOptimized {
    first: u8,
    third: u8,
    second: u16
}

assert_eq!(4, mem::size_of::<FieldStructOptimized>());

// Union size is the size of the largest field.
#[repr(C)]
union ExampleUnion {
    smaller: u8,
    larger: u16
}

assert_eq!(2, mem::size_of::<ExampleUnion>());

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Function std::mem::size_of。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。