Skip to content

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

Closed
@dfreese

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)

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