Rust VS C
head
#include <stdint.h>
#include <stdalign.h>
#include <immintrin.h>
#include <math.h>
#include <stdio.h>use std::mem;
use std::arch::x86_64::*;
use std::f64::consts::PI;strcut
// intptr_t should be the native integer type on most
// sane systems.
typedef intptr_t intnative_t;
typedef struct{
double position[3], velocity[3], mass;
} body;此allow 属性(类似于 a #pragma)通知编译器我们希望允许偏离命名约定
#[repr(C)]标记struct要求 Rust 布局struct 与 C 完全相同 ,没有的话它会优化它们以获得最佳的打包和对齐——这可能是你以前手工完成的。
#defines 可以被 Rust 替换const,它声明了一个常量
函数
在 C 中,bodies[i]完全一样*(bodies + i)——它执行指针算术和解引用,仅此而已。特别是,它假定您有理由知道这i是数组的有效索引。这是 C 语言中的常见情况,可以使用方括号进行速记。
在 Rust 中,常见用例使用引用而不是指针3并进行边界检查,因此用例得到简写bodies[i]。做未经检查的指针算术是例外而不是规则,因此我们必须更加刻意地表达它。
最后,我们必须写*bodies.add(i)而不是*(bodies + i)因为 Rust 不会为指针重载算术运算符。相反,指针提供了add、sub和其他在代码审查中更容易发现的操作;如果您好奇,这里是完整列表。
Last updated