是否可以使用Rust的宏/语法扩展来执行使用静态基元的计算?

时间:2014-10-10 04:25:36

标签: macros static metaprogramming rust

我很想知道是否可以对返回其他静态基元的静态基元执行编译时计算。

例如,像这样:

static FOUR: uint = add!(2u, 2u);
static FORTY_TWO: f32 = div!(84f32, 2f32);

static CHANNELS: uint = 2;
static FRAMES: uint = 256;
static BUFFER_SIZE: uint = mul!(CHANNELS, FRAMES);

如果可能的话,会怎么做呢?

1 个答案:

答案 0 :(得分:3)

是的,它们在编译时进行评估,无需编写宏或语法扩展。

作为证明,以下代码:

static FOUR: uint = 2u + 2u;
static FORTY_TWO: f32 = 84f32 / 2f32;

static CHANNELS: uint = 2;
static FRAMES: uint = 256;
static BUFFER_SIZE: uint = CHANNELS * FRAMES;

导致此LLVM IR:

@_ZN4FOUR20h8a0d12679f3ae402gaaE = internal constant i64 4
@_ZN9FORTY_TWO20h4316db579aa4eb4fmaaE = internal constant float 4.200000e+01
@_ZN8CHANNELS20h8a0d12679f3ae402saaE = internal constant i64 2
@_ZN6FRAMES20h8a0d12679f3ae402waaE = internal constant i64 256
@_ZN11BUFFER_SIZE20h8a0d12679f3ae402AaaE = internal constant i64 512

希望它有所帮助。