88

When talking about imports, the word prelude is used every so often by the rustaceans.

What is this prelude they talk about?

How does it affect my Rust programs?

1 Answer 1

84

In Rust, in order to use a symbol, you must either:

  • have defined the symbol in the current scope
  • have imported the symbol in the current scope via a use directive: use std::mem;
  • be referring to the symbol using its absolute path: std::mem::replace

however, some very few symbols can be used without such actions: Option or Copy for example!

This is due to the Rust prelude.

A number of traits, types and functions were judged to be so frequently used that it made sense not to require that their use required explicitly importing the necessary symbols each and every time. This is achieved thanks to two implicit actions taken by the compiler:

  • at the root of every crate, the compiler injects an implicit extern crate std;
  • in every module, the compiler injects an implicit use std::prelude::v1::*; (for now)

std::prelude::v1 is just a regular module which re-exports those frequently used symbols using the pub use ... syntax. Its exact content can be found here.


A number of other libraries, or even sub-components of the standard library also define a prelude module that you may import with the same glob import syntax: use xxx::prelude::*;. Unlike the std::prelude however those are not special-cased by the compiler and therefore require explicit importing.


The compiler is agnostic to the exact content of the prelude, therefore if one was to replace the std crate with their own (for example, in embedded development) then one would decide what goes into their std::prelude::v1 module.

5
  • 1
    @LukasKalbertodt: Ah good point, I had started writing the answer with vec!, panic!, ... but could not find where those came from. I'll remove it. Commented Apr 3, 2016 at 13:26
  • This RFC proposes to add prelude functionality to user crates. It has been closed some time ago, but might be revived in the future. Commented Apr 3, 2016 at 13:39
  • @MatthieuM. Thanks for the clear explanation. It seems like that println! macro does not come from std::prelude?
    – Jeremy Kao
    Commented May 8, 2016 at 2:55
  • @JeremyKao: It does, if you go to the prelude page it's listed in the macros section. (Just CTRL+F println) Commented May 8, 2016 at 11:48
  • 1
    Thanks! I was using use anchor_lang::prelude::* for ages and wondering where the name came from. Commented Jan 25 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.