0Pricing
Learn Rust Coding · Урок

use и пути

Импорт элементов

«use и пути» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Bringing Items Into Scope

Typing full paths like std::collections::HashMap everywhere is tedious. The use keyword brings an item into scope so you can refer to it by a short name.

A Basic use

After a use, you reference the item by its final name. Here we import HashMap and use it directly.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("ana", 10);
    println!("{:?}", scores.get("ana"));
}

Absolute vs Relative Paths

An absolute path starts from crate (the crate root). A relative path starts from the current module, optionally using self or super.

mod a {
    pub mod b {
        pub fn hi() { println!("hi from b"); }
    }
    pub fn call_b() {
        crate::a::b::hi();
        self::b::hi();
    }
}

fn main() {
    a::call_b();
}

use Inside Modules

A use only affects the scope it appears in. Place it at the top of a module to shorten names used throughout that module.

mod work {
    use std::collections::HashSet;
    pub fn run() {
        let mut s = HashSet::new();
        s.insert(1);
        s.insert(1);
        println!("size {}", s.len());
    }
}

fn main() {
    work::run();
}

Renaming With as

When two items share a name, or a name is too long, rename on import with as.

use std::collections::HashMap as Map;

fn main() {
    let mut m: Map<&str, i32> = Map::new();
    m.insert("x", 1);
    println!("{:?}", m.get("x"));
}

Grouping Imports

Import several items from the same path in one line using braces. This keeps the import block tidy.

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

fn main() {
    let map: HashMap<i32, i32> = HashMap::new();
    let set: HashSet<i32> = HashSet::new();
    println!("{} {}", map.len(), set.len());
}

Nested Groups and self

Inside a group, self imports the module itself alongside its items. This lets you use both the module name and specific members.

use std::io::{self, Write};

fn main() {
    let _ = io::stdout().write_all(b"hello\n");
}

Glob Imports

The glob * brings in everything public from a path. Use it sparingly — it can hide where names come from — but it is common for preludes and tests.

mod colors {
    pub fn red() -> &'static str { "red" }
    pub fn blue() -> &'static str { "blue" }
}

use colors::*;

fn main() {
    println!("{} {}", red(), blue());
}

Idiomatic Import Style

Convention: import functions by their parent module (use std::cmp; cmp::max(...)) but import types by name (use std::collections::HashMap;). This makes calls read clearly.

use std::cmp;

fn main() {
    println!("{}", cmp::max(3, 9));
}

Paths to External Crates

For dependencies, the path starts with the crate name, for example rand::thread_rng. You list the crate in Cargo.toml, then import items the same way you do for std.

Keeping Imports Clean

Group related imports, rename to avoid clashes, and prefer explicit imports over globs in application code. Clean imports make a file easy to scan.

Quick Check

Test your path knowledge.

Recap

You learned to import items:

  • use brings an item into scope by a short name
  • Absolute paths start at crate; relative paths use self/super
  • as renames, braces group, and * globs
  • Import types by name and functions by parent module for clarity

Часто задаваемые вопросы

Урок «use и пути» бесплатный?

Да — полный текст урока «use и пути» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.

Чему я научусь в уроке «use и пути»?

Импорт элементов Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Learn Rust Coding?

Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «use и пути»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Learn Rust Coding?

Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Модули и mod
  2. pub и видимость
  3. use и пути
  4. Крейты и корень крейта
← Назад к Learn Rust Coding