6. Documenting your code

Many software that are built today have source code that are often made up of millions of lines of code. More often than not the software is also worked upon by a large number of programmers. Such large scale development makes it difficult to understand the program without some kind of documentation the describes what it does and why it does what it does.

Mojo supports two ways of documenting code.

6.1. Comments

You can define comments within Mojo source code using the symbol #. Mojo ignores any text that comes after the # until it encounters the end of line. Comments are meant for human consumption and typically explain the context of the code. Comments are discarded by the compiler and do therefore not have any run time presence.

    # This is a comment
    my_function("Hello World!") # This is an inline comment

6.2. Docstrings

One of the important type of documentation is describing what a given function does. You can use Mojo comments for this purpose, but Mojo does not distinguish such comments from the ones that are given in other parts of the source code.

Mojo does provide a facility to document functions (and other type of declarations). It is called Docstring. In a previous chapter it was mentioned that we can define multi line string literals in Mojo using three double or three single quotes. This type of string literals are used to define Docstring.

One requirement for a multi line string literal to be a docstring of a function is that it should be scoped within the function. If it is outside the function, then it is considered to be documentation of the outer scope element. The other requirement is that it should be the first statement in the function body. The text of the multi line string must have at least one full stop. This is because the first sentence of the Docstring is considered as summary of the document and will show up in tooling as such.

fn my_function(text: StringLiteral):
    """
    This is a doc string summary.
    And the second line represents more details.
    """
    print(text)

You can pass the above program to Mojo’s documentation tooling to generate the documentation.

mojo doc <filename>

You can define file level docstring by writing docstring as the first statement of the file. Such docstring is used to document the module itself.

"""
File level docstring.
"""
alias x = 42

fn main():
    print(x)