我跟随quite a bit的the documentation并尝试reuse an example,但我无法让我的代码工作。
我的Cargo.toml看起来像这样:
[package]
name = "Blahblah"
version = "0.3.0"
authors = ["ergh <[email protected]"]
[dependencies]
[[bin]]
name = "target"
path = "src/main.rs"
[features]
default=["mmap_enabled"]
no_mmap=[]
mmap_enabled=[]
我想根据我传递给cargo build
命令的功能配置,使用与mmap不同的缓冲区源本地测试我的代码。我的代码中有这个:
if cfg!(mmap_enabled) {
println!("mmap_enabled bro!");
...
}
if cfg!(no_mmap) {
println!("now it's not");
...
}
编译器没有看到任何一个if
语句体中的代码,所以我知道两个cfg!
语句都在评估为false。为什么?
我读过Conditional compilation in Rust 0.10?,我知道它并不完全重复,因为我正在寻找一个有效的例子。
测试特征的正确方法是feature = "name"
,如果你滚动一点,你可以在the documentation you linked中看到:
至于如何启用或禁用这些开关,如果你正在使用Cargo,它们会被设置在
[features]
section的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 = []
当你这样做时,Cargo将旗帜传递给
rustc
:--cfg feature="${feature_name}"
这些
cfg
标志的总和将决定哪些被激活,因此,哪些代码被编译。我们来看看这段代码:#[cfg(feature = "foo")] mod foo { }
在你的情况下使用cfg!
宏,这将映射到cfg!(feature = "foo")
。