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

3
我是一名有用的助手,可以为您进行文本翻译。

我已经阅读了相当多文档并尝试重用一个示例, 但我的代码无法运行。

我的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=[]

我想通过在命令中传递不同的特性配置来使用与mmap不同的缓冲区起点本地测试我的代码。我在我的代码中有这样的内容:

if cfg!(mmap_enabled) {
    println!("mmap_enabled bro!");
    ...
}
if cfg!(no_mmap) {
    println!("now it's not");
    ...
}

编译器没有看到任何一个if语句体中的代码,所以我知道两个cfg!语句都评估为false。为什么?
我已经阅读了Rust 0.10中的条件编译?,我知道这不是一个完全相同的问题,因为我正在寻找一个可行的示例。

顺便提一下,互斥的功能应该使用单个功能而不是两个独立的功能来完成,例如测试 feature = "mmap"not(feature = "mmap")。具体来说,创建的用户可以同时启用 no_mmapmmap_enabled,这似乎可能会有问题。 - huon
我已经考虑过这个问题,1)该软件包是内部的,2)代码是独占的,也就是说如果其中一个没有被评估,另一个也不会被评估。 - Adam Miller
很酷!听起来你已经掌控了一切。(只是想确保你知道这些权衡。) - huon
1个回答

5

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

As for how to enable or disable these switches, if you’re using Cargo, they get set in the [features] section of your 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 = []

When you do this, Cargo passes along a flag to rustc:

--cfg feature="${feature_name}"

The sum of these cfg flags will determine which ones get activated, and therefore, which code gets compiled. Let’s take this code:

#[cfg(feature = "foo")]
mod foo {
}
在您的情况下,使用 cfg! 宏,这将映射到 cfg!(feature = "foo")

1
这就是如何包含或排除整个模块。但是我有一小段代码必须在函数中间进行替换。所以那种语法和定义不适用。 - Adam Miller
我明白。我在这里强调的是如何测试“功能”的语法,即 cfg 中的内容。它应该是 feature = "name",而不仅仅是 cfg(name) - Jorge Israel Peña
当你写下那个回答时,我正在为自己的问题写答案。你指出了正确的做法。 - Adam Miller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接