Best practice of extending a no_std crate

I know it's mentioned in the api guidelines crate which currently resides in the nursery (GitHub repo).

Do not include words in the name of a Cargo feature that convey zero meaning, as in use-abc or with-abc. Name the feature abc directly.

This arises most commonly for crates that have an optional dependency on the Rust standard library. The canonical way to do this correctly is:

# In Cargo.toml

[features]
default = ["std"]
std = []
// In lib.rs
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
fn some_function_which_requires_std() -> HashMap<u32, String> {
  ...
}

Something you may want to do is create a "facade" module which acts somewhat like a union over core and std so you don't have to ugly #[cfg(feature = "std")] switches all over the place when importing things. Check out serde's lib.rs for a real life example.

5 Likes