std, primitives and preludes
⭐️ In Rust, language elements are implemented by not only std
library crate but also compiler as well. Examples,
Primitives : Defined by the compiler and methods are implemented by
std
library directly on primitives.Standard Macros : Defined by both compiler and
std
std
library has been has divided into modules, according to the main areas each covered.
⭐️ While primitives are implemented by the compiler, the standard library implements most useful methods directly on the primitive types. But some rarely useful language elements of some primitives are stored on relevant std
modules. This is why you can see char
, str
and integer types on both primitives and std
modules.
Primitives
Standard Macros
Std Modules
🔎 When examine Rust’s source code, you can see that
src
directory is a workspace. Even though its having many library crates, by examine root Cargo.toml file you can easily identify that main crates are rustc(compiler) and libstd (std). In libstd/lib.rs std modules have been re-exported viapub use
and the original location of most of std modules issrc/libcore
.
Few important std
modules are,
std::io
- Core I/O functionalitystd::fs
- Filesystem specific functionalitystd::path
- Cross platform path specific functionalitystd::env
- Process’s environment related functionalitystd::mem
- Memory related functionalitystd::net
- TCP/UDP communicationstd::os
- OS specific functionalitystd::thread
- Native threads specific functionalitystd::collections
- Core Collection types
💯 Refer Rust Standard Library Documentation for more details.
Preludes
Even though Rust std
contains many modules, by default it doesn’t load each and every thing of std library on every rust program. Instead, it loads only the smallest list of things which require for almost every single Rust program. These are called preludes. They import only,
Preludes have been imported explicitly on
libstd/lib.rs
and the whole list can be seen onlibstd/prelude/v1.rs
.
⭐️ So technically, Rust inserts,
extern crate std;
: into the crate root of every crateuse std::prelude::v1::*;
: into every moduleSo you don’t need to import these each time.
The concept of preludes is quite common on Rust libraries. Even some modules inside std
crate (ex.libstd/io) and many libraries (ex. diesel) are having their own prelude
modules.
⭐️ But preludes are used to create a single place to import all important components which are required while using the library. They do not load automatically unless you imported them manually. Only std::prelude
imports automatically in every Rust programs.
Last updated