DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • rust

    • Rust
    • add
    • 属性(attributes)
    • cargo issue
    • cli
    • build.rs
    • Enums
    • eventEmitter(rust)
    • 格式化输出 std::fmt
    • rust iterator
    • rust 学习计划
    • 生命周期(lifetime)
    • Linked List
    • log
    • macros
    • mem::size_of
    • niche optimization
    • Rust 所有权
    • 模式匹配(pattern matching)
    • module system
    • result & option
    • .rust-analyzer.json
    • rust startup
    • rust-test
    • 可见性(visibility)
    • cargo
    • toml

mem::size_of

struct

为了更好地理解 Rust 中的内存对齐,我们可以通过图示来展示结构体字段在内存中的布局。我们以 FieldStruct 为例,该结构体定义如下:

struct FieldStruct {
    first: u8,
    second: u16,
    third: u8,
}

内存布局示意图

  1. 字段 first:

    • 大小:1 字节
    • 对齐:1 字节
  2. 填充:

    • second 字段需要 2 字节对齐,因此在 first 之后需要填充 1 字节。
  3. 字段 second:

    • 大小:2 字节
    • 对齐:2 字节
  4. 字段 third:

    • 大小:1 字节
    • 对齐:1 字节
  5. 填充:

    • 结构体的总大小需要是其最大对齐单位的整数倍(即 2 字节的倍数),因此在 third 之后需要填充 1 字节。

内存布局图示

| first (u8) | padding | second (u16) | third (u8) | padding |
| ---------- | ------- | ------------ | ---------- | ------- |
| 1          | 1       | 2            | 1          | 1       |

内存布局步骤

  1. first 字段:大小为 1 字节,对齐为 1 字节。

    | first (u8) |
    | ---------- |
    | 1          |
    
  2. 填充:为了使 second 字段对齐,需要填充 1 字节。

    | first (u8) | padding |
    | ---------- | ------- |
    | 1          | 1       |
    
  3. second 字段:大小为 2 字节,对齐为 2 字节。

    | first (u8) | padding | second (u16) |
    | ---------- | ------- | ------------ |
    | 1          | 1       | 2            |
    
  4. third 字段:大小为 1 字节,对齐为 1 字节。

    | first (u8) | padding | second (u16) | third (u8) |
    | ---------- | ------- | ------------ | ---------- |
    | 1          | 1       | 2            | 1          |
    
  5. 填充:为了使结构体的总大小是最大对齐单位(2 字节)的整数倍,需要在末尾填充 1 字节。

    | first (u8) | padding | second (u16) | third (u8) | padding |
    | ---------- | ------- | ------------ | ---------- | ------- |
    | 1          | 1       | 2            | 1          | 1       |
    

结论

最终 FieldStruct 的内存布局大小为 6 字节。通过图示,我们可以直观地看到字段和填充字节在内存中的排列方式,从而理解内存对齐的概念。

验证代码

use std::mem;

struct FieldStruct {
    first: u8,
    second: u16,
    third: u8,
}

fn main() {
    assert_eq!(6, mem::size_of::<FieldStruct>());
    println!("Size of FieldStruct: {}", mem::size_of::<FieldStruct>());
}

运行上述代码,确认 FieldStruct 的大小确实为 6 字节。

Last Updated:
Contributors: rosendo
Prev
macros
Next
niche optimization