gocode-documentation

What is the proper way to write a code block in a Go function comment?


I want to include some example codes in my comment for a function, like this:

// Some example for using `foo`:
//
// ```
//   f := Foo(...)
//   g := Goo(f)
// ```
func Foo() {
  ...
}

But the code block is not displayed properly in VS Code. What is the proper way to do it?


Solution

  • Remove those backticks and just indent the code:

    // Foo does ... (note this first line)
    // Some example for using Foo:
    //
    //   f := Foo(...)
    //   g := Goo(f)
    func Foo() {
      ...
    }
    

    Quoting from The Go Blog: Godoc: documenting Go code:

    There are a few formatting rules that Godoc uses when converting comments to HTML:

    • Subsequent lines of text are considered part of the same paragraph; you must leave a blank line to separate paragraphs.
    • Pre-formatted text must be indented relative to the surrounding comment text (see gob's doc.go for an example).
    • URLs will be converted to HTML links; no special markup is necessary.

    Related topics: