Julia Documenting Code
Documenting code is writing a short note above a definition that explains what it does. The note helps a later reader use the definition without guessing.
A documented function still returns its value
A docstring sits above the function. The call below prints the returned sum.
"""
Return the sum of two numbers.
"""
function add_two(a, b)
return a + b
end
println(add_two(4, 5))A docstring can describe a single-value function
The note states the result in plain words. The call below prints the square.
"""
Return the square of a number.
"""
function square_number(x)
return x * x
end
println(square_number(6))A docstring can describe a function with two inputs
The note names the shape the function measures. The call below prints the area.
"""
Return the area of a rectangle.
"""
function rectangle_area(w, h)
return w * h
end
println(rectangle_area(3, 7))Example
"""
Return the sum of three numbers.
"""
function sum_three(a, b, c)
return a + b + c
end
println(sum_three(10, 20, 30))Key points
- Docstring: a triple-quoted note placed directly above a definition.
- Placement: the note must sit directly above the definition it describes.
- Use a docstring to state what a function returns in plain words.
- Content: keep the note short and focused on a single purpose.
- Reader: a reader can learn the purpose without reading the body.
In this example, a docstring states the return value in plain words. The function adds three numbers. The call prints 60.
Note
a docstring is text, and it does not change what the function returns.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Where does a docstring sit?