如何在 Rust 中使用条件编译宏的示例 [英] Example of how to use Conditional Compilation Macros in Rust

查看:44
本文介绍了如何在 Rust 中使用条件编译宏的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了相当多文档 并试图重用示例,但我的代码无法运行.

I've followed quite a bit of the documentation and tried to reuse an example, but I can't get my code to work.

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

My Cargo.toml looks like this:

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

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

I'd like to test my code locally with a different buffer origin than mmap based on what feature configuration I pass to the cargo build command. I have this in my code:

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

编译器看不到 if 语句主体中的代码,所以我知道 cfg! 语句的计算结果为 false.为什么?

The compiler doesn't see the code in either of the if statement bodies, so I know that both of the cfg! statements are evaluating to false. Why?

我已经阅读了 Rust 0.10 中的条件编译? 并且我知道它不是完全重复,因为我正在寻找一个有效的例子.

I've read Conditional compilation in Rust 0.10? and I know it's not an exact duplicate because I'm looking for a functioning example.

推荐答案

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

The correct way to test for a feature is feature = "name", as you can see in the documentation you linked if you scroll a bit:

至于如何启用或禁用这些开关,如果您使用的是 Cargo,它们在 [features]<中设置Cargo.toml 的/code> 部分:

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

当你这样做时,Cargo 将一个标志传递给 rustc:

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

--cfg feature="${feature_name}"

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

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").

In your case using the cfg! macro, this would map to cfg!(feature = "foo").

这篇关于如何在 Rust 中使用条件编译宏的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆