mem::zeroed() 函数
这个函数类似于 libc 中的 bzero(), 将一个结构体中的所有字节都置为 0.
比如, 下面的一个示例程序:
use std::mem;
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Point {
pub x: i32,
pub y: i32,
}
fn main() {
let zeroed_point: Point = unsafe { mem::zeroed() };
let default_point = Point::default();
assert_eq!(zeroed_point, default_point);
}
对应的 C 代码如下:
#include <assert.h>
#include <stdint.h>
#include <string.h>
struct point_s {
int32_t x;
int32_t y;
};
typedef struct point_s point_t;
int main(int argc, char** argv) {
point_t zeroed_point;
bzero(&zeroed_point, sizeof(point_t));
point_t default_point = {.x = 0, .y = 0};
return 0;
}