String interpolation in docstring

Hey community :slight_smile:

That’s probably a quick question. I’m writing docstrings and want to show an little example like

"""
    f(s::String)::Nothing
# Example
for i in 1:10
    f("i = $i")
end
"""
function f(s::String)
    println(s)
end

But I can’t compile it because i is not known. Is there a easy fix?

Easy fix:

"""
    f(s::String)::Nothing
# Example
```julia
for i in 1:10
    f("i = $1")
end
\```
"""
function f(s::String)
    println(s)
end

Note that added an extraneous escape \ just after end so that the markup here will render.

This will only render your example, and not try to run it in the documentation context.

The problem is that you want the $ to show up in the docs rather than perform interpolation? If so use \$ like this

"""
    f(s::String)::Nothing
# Example
```julia
for i in 1:10
    f("i = \$i")
end
```
"""
function f(s::String)
    println(s)
end
5 Likes

An alternative is to use a raw string literal, but then you need to explicitly call @doc:

@doc raw"""
    f(s::String)::Nothing
# Example
```julia
for i in 1:10
    f("i = $1")
end
```
"""
function f(s::String)
    println(s)
end
2 Likes

That doesn’t work for me. Why is the \ at the end?

julia> """
           f(s::String)::Nothing
           # Example
       ```julia
       for i in 1:10
           f("i = $1")
ERROR: syntax: invalid interpolation syntax: "$1"
Stacktrace:
 [1] top-level scope at none:0

julia> end
ERROR: syntax: unexpected "end"
Stacktrace:
 [1] top-level scope at none:0

julia> \```
ERROR: syntax: "\" is not a unary operator
Stacktrace:
 [1] top-level scope at none:0

julia> """
       function f(s::String)
           println(s)
       end

Just delete the \ in your code. I put it there because the markdown wasn’t rendering on this forum for me with a nested ```

Oh now I see. But it still won’t work for me… Have you tried it in a file?

That works as well :+1:

https://docs.julialang.org/en/v1/manual/documentation/

Docstrings are meant to be used in files, not sure if trying it in REPL is going to work. Try the exact syntax in the Julia manual. Works for me.

That works as well :+1:
thy

But the problem is the $. It tries to use $i

1 Like