Learning Golang: Comments

Share on:

This is part 5 of my journey learning Golang.

Inline comments

Go ignores text to the right of //:

1// This entire line is ignored by the compiler.
2// fmt.Println("Does NOT print")
3fmt.Println("This gets printed!") // This part gets ignored

Block comments

All lines between /* and */ will be ignored:

1/*
2This is ignored.
3This is also ignored.
4fmt.Println("This WON'T print!")
5*/

Godoc

Go has a tool for automatically generating documentation from Go source code: Godoc.

From the blog post that announced it in 2011:

Godoc parses Go source code - including comments - and produces documentation as HTML or plain text.

See an example in HTML format: zip - GoDoc.

Godoc follows some simple conventions.

Package comments

This type of comment should be present in one of the source files of a package:

1// Package sort provides primitives for sorting slices and user-defined
2// collections.
3package sort

Top-level identifier comments

This is the format for describing a top-level function, const, var, etc.:

1// enterOrbit causes Superman to fly into low Earth orbit, a position
2// that presents several possibilities for planet salvation.
3func enterOrbit() os.Error {
4  ...
5}

Code samples in comments

Indented text inside of a comment will be rendered as a pre-formatted block by Godoc:

 1// fight can be used on any enemy and returns whether Superman won.
 2//
 3// Examples:
 4//
 5//  fight("a random potato")
 6//  fight(LexLuthor{})
 7//
 8func fight(enemy interface{}) bool {
 9  ...
10}

Bug comments

Godoc ignores most comments that are not right above a top-level element. A bug comment is an exception: it will be included in the package’s documentation under a “Bugs” section:

1// BUG(name): The rule Title uses for word boundaries does not handle Unicode punctuation properly.

The text in the parenthesis block is the user name of someone that can provide more information about the bug.

Deprecation notes

Elements that became redundant or obsolete can be marked with a paragraph in their doc comments that begins with “Deprecated:” followed by some information about the deprecation:

1// ModTime returns the modification time in UTC using the legacy
2// ModifiedDate and ModifiedTime fields.
3//
4// Deprecated: Use Modified instead.
5func (h *FileHeader) ModTime() time.Time {
6  return msDosTimeToTime(h.ModifiedDate, h.ModifiedTime)
7}

comments powered by Disqus