Важные темы Rust

Rust Modules and pub

Organize code into modules and decide what the rest of the program may use.

  • Продвинутый
  • Чтение: 3 мин
  • Примеров для запуска: 1
Что вы узнаете
  • mod and pub
  • Paths with ::
  • use and super
mod geometry
  • geometry
    • pub circle_areapublic
    • squareprivate
    • pub mod convertto_degrees

Private unless marked pub

A module groups related functions, types and constants under a name. Everything in a module is private unless it is marked pub, so a module can hide its details.

circle_area is public, but square is private and can only be called inside geometry. Paths use ::, and super refers to the parent module. use brings a name into scope so to_degrees can be called without its full path.

Главное

  1. Everything in a module is private by default.
  2. pub makes an item usable from outside.
  3. use brings a name into scope.

Пример на Rust, который можно запустить

Rust
Запустить код →
main.rs
mod geometry {
    pub const PI: f64 = 3.14159;

    pub fn circle_area(radius: f64) -> f64 {
        PI * square(radius)
    }

    fn square(value: f64) -> f64 {
        value * value
    }

    pub mod convert {
        pub fn to_degrees(radians: f64) -> f64 {
            radians * 180.0 / super::PI
        }
    }
}

use geometry::convert::to_degrees;

fn main() {
    println!("{:.2}", geometry::circle_area(2.0));
    println!("{:.1}", to_degrees(geometry::PI));
}
Получить кнопку запуска для этого примера Результат выполнения
12.57
180.0

Практика

Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.

Закончили этот урок?

Отметьте его как изученный, чтобы следить за прогрессом.

Далее: Threads →

Попрактикуйтесь на задаче

Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.

Все задачи