Skip to content

Use of feature flagged functions in std::cfg macro #71679

Closed

Description

@dfreese

I tried this code:

#[cfg(feature = "enabled")]
pub fn conditionally_enabled() -> i64 {
    42
}

pub fn always_enabled() -> i64 {
    9001
}

pub fn integration() -> i64 {
    if cfg!(feature = "enabled") {
        conditionally_enabled()
    } else {
        always_enabled()
    }
}

I expected to see this compile based on the std::cfg macro docs, instead, this it failed to compile. This was confusing, as I was able to write this, in a slightly less clear way, using cfg attributes. The documentation calls out the links between the two, saying The syntax given to this macro is the same syntax as the cfg attribute.

Should the docs for std::cfg be updated to state that both branches of the if/else need to be valid regardless of the cfg! condition? Or is this something that would be expected to compile?

Meta

This was tested on 1.42.0, but from compiler explorer, this shows up in all versions since 1.0.0
rustc --version --verbose:

rustc 1.42.0 (b8cedc004 2020-03-09)

Activity

  1. Mark-Simulacrum commented on Apr 29, 2020

    @Mark-Simulacrum
    Member

    We can update the docs, for sure, but I'm not sure what to say -- maybe something like "this simply evaluates to true/false"? cfg! is basically not special to the compiler, it doesn't ever remove code, so everything still needs to compile (unlike #[cfg(...)] which will remove code if the expression doesn't evaluate to true).

  2. added
    C-enhancementCategory: An issue proposing an enhancement or a PR with one.
    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and tools
    E-help-wantedCall for participation: Help is requested to fix this issue.
    and removed
    C-bugCategory: This is a bug.
    on Apr 29, 2020
  3. dfreese commented on Apr 29, 2020

    @dfreese
    ContributorAuthor

    To rephrase, slightly, how about adding the following to the docs:

    cfg!, unlike #[cfg(...)], does not remove any code and only evaluates to true or false. For example, this means all code in an if/else block needs to be valid when cfg! is used for the condition, regardless of what cfg! is evaluating.

  4. added a commit that references this issue on Apr 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-help-wantedCall for participation: Help is requested to fix this issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions