Комментарии к документации
Документация ///
«Комментарии к документации» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Documentation in Rust
Rust has first-class documentation built into the language. Special comments become HTML docs generated by cargo doc.
Outer Doc Comments
Use /// to document the item that follows it — functions, structs, enums, and more. The text supports Markdown.
/// Adds two numbers together.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Markdown Formatting
Doc comments render Markdown: headings, lists, bold, and links all work. Inline code uses backticks, and section headings start with #.
/// Computes the area of a rectangle.
///
/// # Arguments
/// * width - the width
/// * height - the height
pub fn area(width: u32, height: u32) -> u32 {
width * height
}Common Doc Sections
Conventional headings make docs scannable:
# Examples— usage samples# Panics— when it panics# Errors— what errors it returns# Safety— invariants for unsafe code
Inner Doc Comments
Use //! to document the enclosing item, typically a module or the whole crate. Place it at the top of the file.
//! # My Math Crate
//!
//! Utilities for basic arithmetic.
pub fn double(n: i32) -> i32 {
n * 2
}Documenting Structs and Fields
Each public item, including struct fields, can have its own doc comment.
/// A point in 2D space.
pub struct Point {
/// The horizontal coordinate.
pub x: f64,
/// The vertical coordinate.
pub y: f64,
}Generating Docs
cargo doc builds HTML documentation into target/doc. Add --open to view it in your browser.
cargo doc --openExcluding Dependencies
By default Cargo also documents your dependencies. Use --no-deps to build docs for your crate only.
cargo doc --no-deps --openIntra-Doc Links
Link to other items by writing their path inside square brackets. Rust resolves the path and creates a clickable link in the generated docs.
/// See also [add] for addition.
///
/// [add]: crate::add
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}Why Document?
Good docs pay off:
- Generated automatically into searchable HTML
- Published to docs.rs for free when you publish a crate
- Examples in docs are tested (doc tests)
- Helps teammates and future you
Documenting a Module
Combine inner and outer comments: a module file opens with //! describing the module, and each item inside uses ///.
//! Geometry helpers.
/// Returns the perimeter of a square.
pub fn perimeter(side: f64) -> f64 {
side * 4.0
}Quick Check
Which comment syntax documents the item that comes right after it?
Recap
You learned doc comments:
///documents the following item;//!documents the enclosing one- They support Markdown and sections like
# Examples - Intra-doc links connect items
cargo doc --opengenerates and views HTML docs
Часто задаваемые вопросы
Урок «Комментарии к документации» бесплатный?
Да — полный текст урока «Комментарии к документации» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.
Чему я научусь в уроке «Комментарии к документации»?
Документация /// Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Learn Rust Coding?
Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Комментарии к документации»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Learn Rust Coding?
Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Модульные тесты
- Интеграционные тесты
- Комментарии к документации
- Тесты документации