Comments
In this chapter, we'll explore document your code with single-line and multi-line comments.
Comments
All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave comments in their source code that the compiler ignores but people reading the source code may find useful.
Here's a simple comment:
// hello, worldIn Mana, the idiomatic comment style starts with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you'll need to include // on each line:
// So we're doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what's going on.Inline Comments
Comments can also be placed at the end of lines containing code:
let lucky_number = 7 // I'm feeling lucky todayBut you'll more often see comments above the code they annotate:
// I'm feeling lucky today
let lucky_number = 7Multi-line Comments
Mana also supports multi-line comments using /* and */:
/* This is a multi-line comment.
It can span several lines.
Very useful for longer explanations. */Multi-line comments can also be used inline:
let x = 5 /* the number of tries */ + 10Documentation Comments
Mana has a special kind of comment for documentation, called doc comments:
/// Calculates the area of a rectangle.
///
/// # Arguments
/// * `width` - The width of the rectangle
/// * `height` - The height of the rectangle
///
/// # Returns
/// The area as a floating-point number
///
/// # Example
/// ```mana
/// let area = calculate_area(10.0, 5.0)
/// assert_eq(area, 50.0)
/// ```
pub fn calculate_area(width: f64, height: f64) -> f64 {
return width * height
}Doc comments start with /// and support Markdown formatting. These comments generate documentation that can be viewed in IDEs and extracted into standalone documentation.
Module Documentation
Use //! for documentation that applies to the containing module:
//! # Math Utilities
//!
//! This module provides common mathematical operations.
//!
//! ## Examples
//!
//! ```mana
//! use math.add
//! let sum = add(2, 3)
//! ```
module math
/// Adds two numbers together.
pub fn add(a: int, b: int) -> int {
return a + b
}Comment Best Practices
Good comments explain why, not what:
// Bad: Increment i by 1
i = i + 1
// Good: Move to next user in the list
i = i + 1Comments should add information that isn't obvious from the code itself:
// Bad: Check if x is greater than 10
if x > 10 {
// ...
}
// Good: Users with more than 10 posts are considered active
if post_count > 10 {
mark_as_active(user)
}TODO Comments
Mark unfinished work or planned improvements:
// TODO: Add error handling for network failures
fn fetch_data(url: string) -> string {
// ...
}
// FIXME: This is O(n²), optimize for large datasets
fn process_items(items: Vec<Item>) -> void {
// ...
}Now let's explore Control Flow.