rust

Is there any disadvantage to referencing modules through `core` or `alloc` instead of `std`?


Rust's standard library is exposed as three packages: std, alloc, and core. In terms of API, the functionality in core is the subset of std that can be supported without depending on any operating system integration or heap allocation. alloc falls between them, with functionality that depends on heap allocations but no other operating system integration. When writing imports for my libraries, I've been tempted to always refer to modules via the more-compatible core or alloc instead of std, if they're available.

However, it's been unclear to me whether their implementations of the same functionality could vary. If I use core::cell::RefCell, could I get an implementation that's less efficient than if I'd referred to std::cell::RefCell?

Is there any disadvantage to referencing modules through core or alloc instead of std if they're available?


Solution

  • Rust aims to be a general purpose language that can run on many kinds of architectures (x86_64, i686, PowerPC, ARM, RISC-V) and systems (Windows, macOS, Linux) and even embedded systems with no Operating System.

    But when you don't have an OS, you don't necessarily have a memory allocator or file handling, because those are things a OS would normally do.

    This is where #![no_std] comes into play. If you put that directive in your lib.rs, you will tell the Rust compiler to not link the std crate, but only use core instead. As you said, core is a subset of std and has (mostly) everything that does not require allocation of memory or other things that require an underlying OS.

    There is no difference in the actual implementation though. If the function is provided in core, the function in std is just an reexport.

    TL;DR: Use std if you have an Operating System running, else use core. There is no need to mix them.