Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The use declaration

Reference for Rust use: importing items, nested paths, renaming with as, glob imports, pub use re-exports, use self, enum variants and precise capturing.

A use declaration creates a shortcut: it binds a name in the current scope to an item somewhere else, so you can write HashMap instead of std::collections::HashMap. It does not load code; that is the job of mod and of the crates your project depends on.

use can appear in any block, not only at the top of a file, and it affects only the scope that contains it.

Rust
use std::collections::{HashMap, HashSet};

Try it

Rust Paths, groups, renames and globs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Scoped imports and re-exports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
use path::to::Item;
use path::{A, B as C, self, sub::D};
use path::*;
use path::Trait as _;
pub use path::Item;             // re-export
pub(crate) use path::Item;
use ::crate_name::Item;         // leading :: = external crate
Part Description
{...} Groups several imports under a common prefix; nesting is allowed.
self in a group Imports the prefix itself: use std::fmt::{self, Display}; binds fmt and Display.
as name Renames the binding. as _ imports a trait's methods without a name, which avoids clashes.
* Glob import: all public items (or all variants of an enum).
pub use Makes the imported name part of this module's public interface.

Usage notes

  • Paths start from a crate name (std, serde), from crate, self or super, or from a name already in scope. In edition 2018+ a path in use can start with any in-scope name.
  • Traits must be in scope to call their methods; that is the most common reason for a "method not found" error that a use fixes.
  • Types and values have separate namespaces. One use can import both a function and a type that share a name.
  • Globs hide origins. Prefer explicit imports in library code; globs are fine for preludes (use super::*; in tests, use mylib::prelude::*;).
  • Shadowing. Local items and explicit imports win over glob imports. Two glob imports of the same name conflict only if the name is used.
  • Unused imports trigger a warning. Remove them or use #[allow(unused_imports)] for intentional re-exports.
  • Convention: import types and traits directly, but functions through their module (use std::fs; then fs::read_to_string) so the origin stays visible.