如何在Rust中使用条件编译宏的示例

Ada*_*ler 3 rust

我已经遵循了不少文件,并试图重用一个例子,但我不能让我的代码工作.

我的Cargo.toml看起来像这样:

[package]
name = "Blahblah"
version = "0.3.0"
authors = ["ergh <derngummit@ahwell.com"]
[dependencies]

[[bin]]
name = "target"
path = "src/main.rs"

[features]
default=["mmap_enabled"]
no_mmap=[]
mmap_enabled=[]
Run Code Online (Sandbox Code Playgroud)

我想根据我传递给cargo build命令的功能配置,使用与mmap不同的缓冲区来本地测试我的代码.我的代码中有这个:

if cfg!(mmap_enabled) {
    println!("mmap_enabled bro!");
    ...
}
if cfg!(no_mmap) {
    println!("now it's not");
    ...
}
Run Code Online (Sandbox Code Playgroud)

编译器没有看到任何一个if语句体中的代码,所以我知道这两个cfg!语句都在评估为false.为什么?

在Rust 0.10中读过条件编译?我知道这不是一个完全重复,因为我正在寻找一个有效的例子.

Jor*_*eña 5

测试功能的正确方法是feature = "name",如果滚动一下,您可以在链接的文档中看到:

至于如何启用或禁用这些开关,如果您使用的是货物,则可以在以下[features]部分中进行设置Cargo.toml:

[features]
# no features by default
default = []

# Add feature "foo" here, then you can use it. 
# Our "foo" feature depends on nothing else.
foo = []
Run Code Online (Sandbox Code Playgroud)

当你这样做时,Cargo将旗帜传递给rustc:

--cfg feature="${feature_name}"
Run Code Online (Sandbox Code Playgroud)

这些cfg标志的总和将决定哪些标志被激活,因此,哪些代码被编译.我们来看看这段代码:

#[cfg(feature = "foo")]
mod foo {
}
Run Code Online (Sandbox Code Playgroud)

在您使用cfg!宏的情况下,这将映射到cfg!(feature = "foo").