Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> it is often better to use if cfg!(...) instead of #[cfg(...)] because code behind the latter is eliminated very early

My experience with this is the other way around, especially if you have crates tied to that feature.

The cfg! is a marco that compiles to true/false, so whatever is inside of the if guard needs to compile regardless.

E.g.:

Cargo.toml

    [features]
    default = []
    my_feature = ["deps:feature_dependency"]

    [dependencies]
    feature_dependency = "1.0.0"
And in code:

    if cfg!(feature = "my_feature") {
        feature_dependency::something::Something::invoke();
    }
This will fail if you compile without `my_feature`.


That was the point. The paragraph is talking about how errors only show up in some configurations, leading to “works for me” behavior for some of the devs. When you can get away with cfg!, you are more confident that it will at least compile regardless of the config being checked.


I might be wrong but most optimizing compilers will treat "if false" and the following code as dead and remove it.


It will remove it, but not until after resolving symbols. If the branch-never-taken references a missing library then this will still error, which is the problem for a feature flag.


Fairly sure you’re agreeing with what you quoted




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: