本文介绍了使用 `cfg!` 宏在多个实现之间进行选择的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Cargo.toml 中指定了一些特性:

[特性]复杂 = []简单 = []

当我构建我的项目时,我使用 cargo build --features="complex"simple.

在某些函数中,我想根据使用的功能返回一个值:

fn test() ->u32 {让 x: u32 = 3;if cfg!(feature = "complex") {让 y: u32 = 2;x + y}if cfg!(feature = "simple") {让 y: u32 = 1;x + y}}

但这不起作用,因为它试图评估两个表达式.在我的情况下,使用 cfg! 宏的正确方法是什么?

解决方案

cfg! 的文档说明:

配置标志的布尔评估.

这意味着 cfg!(...) 被替换为布尔值 (true/false).展开后,您的代码将如下所示:

fn test() ->u32 {让 x = 3;如果属实 {让 y = 2;x + y}如果属实 {让 y = 1;x + y}}

最简单的解决方案是添加一个else:

fn test() ->u32 {让 x = 3;if cfg!(feature = "complex") {让 y = 2;x + y} 别的 {让 y = 1;x + y}}

你也可以使用cfg的属性形式.在这种情况下,该属性可以阻止整个下一个表达式被编译:

fn test() ->u32 {让 x: u32 = 3;#[cfg(feature = "complex")]{让 y: u32 = 2;x + y}#[cfg(feature = "simple")]{让 y: u32 = 1;x + y}}

因为它试图对两个表达式求值.

不,没有.评估发生在运行时,甚至无法编译此代码.

另见:

I have specified a few features inside Cargo.toml:

[features]
complex = []
simple = []

When I build my project I use cargo build --features="complex" or simple.

In some functions, I want to return a value based on which feature is used:

fn test() -> u32 {
    let x: u32 = 3;
    if cfg!(feature = "complex") {
        let y: u32 = 2;
        x + y
    }
    if cfg!(feature = "simple") {
        let y: u32 = 1;
        x + y
    }
}

But this doesn't work as it tries to evaluate both expressions. What is the proper way to use the cfg! macro in my case?

解决方案

The documentation for cfg! states:

That means that cfg!(...) is replaced with a Boolean (true / false). Your code would look something like this, after it's expanded:

fn test() -> u32 {
    let x = 3;
    if true {
        let y = 2;
        x + y
    }
    if true {
        let y = 1;
        x + y
    }
}

The easiest solution is to add an else:

fn test() -> u32 {
    let x = 3;
    if cfg!(feature = "complex") {
        let y = 2;
        x + y
    } else {
        let y = 1;
        x + y
    }
}

You can also use the attribute form of cfg. In this case, the attribute can prevent the entire next expression from being compiled:

fn test() -> u32 {
    let x: u32 = 3;

    #[cfg(feature = "complex")]
    {
        let y: u32 = 2;
        x + y
    }

    #[cfg(feature = "simple")]
    {
        let y: u32 = 1;
        x + y
    }
}

No, it doesn't. Evaluation occurs at run-time, and this code cannot even be compiled.

See also:

这篇关于使用 `cfg!` 宏在多个实现之间进行选择的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:35