No_std with feature flag : two ways?

To make a crate no_std with a feature flag I saw two ways to achieve this :


#[cfg(feature = "std")]
extern crate std;


#![cfg_attr(not(feature = "std"), no_std)]

Is there any difference between those ?

I would always choose this method, as most popular crates (serde, time and log just to name a few) do. Enabling no_std while still using the standard library also seems confusing and illogical.


The difference between the two methods is that the second one has the std prelude enabled when the feature is (putting names like Vec implicitly in scope). Therefore, I recommend the first one, because it makes all of your std uses require an actual std::whatever path. If you use the second option, then you could accidentally introduce a use of an item from std and not notice if you don't run a build with the feature disabled.

Another consideration is if you want to support depending on alloc but not std. In that case you must use both no_std and extern crate alloc, and the cfg setup will be simpler if you treat std in the same way as alloc.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.