Associative commentary follow up

This post is a follow up to Friday’s post on comments in Go.

Keith Rarick and Nate Finch pointed out that I had neglected to include two important practical use cases.

Build tags

I’ve previously written about how to use // +build tags to perform conditional compilation. In light of the previous post it’s probably worth recapping them here.

  • Build tags must use the // form.
    // +build right
    /* +build wrong */
  • Build tags must be their own comment, they must not be associated with a declaration.
    // Copyright Microsoft 1981
    // +build !darwin
    // Package basic implements Dartmouth's BASIC interpreter.  
    package basic
  • Build tags must occur early in the file. Only the first few lines of the file are scanned when filtering files by build tags.
    package wrong
    import "io"
    // +build whoops too,late

Copyright headers

The second is managing procedural issues if your licence requires you to include a copyright block at the top of source.

This was also briefly covered in the conditional compilation article. To recap

  • Most licences that recommend copyright headers require them to be at the top of the file, this means they must come before a package declaration, and its comment.
  • You probably don’t want the copyright header being part of your godoc, so the comment block holding the copyright header and the package declaration should be separated by a newline.
  • If you have any build tags, they should also appear between the copyright block and the package declaration. As all three are separate comment, they should be separated by a newline.
    // Copyright Commodore Inc, 1982
    // +build 6502
    // Package c64 is the computer for the masses, not the classes.
    package c64
  • If this leads to a verbose combination of copyright header, build tag, and package comment for godoc, consider moving the comment on the package declaration to a separate file. This is traditionally named doc.go and contains only the package declaration and its commentary.

2 thoughts on “Associative commentary follow up

  1. Russ Cox

    “Build tags must occur early in the file. Only the first few lines of the file are scanned when filtering files by build tags.” is a little vague. In Go source files, the rule is that the // +build comment must occur before the package statement and must not be in the package doc comment. (Because +build comments can appear in non-Go source files as well, the equivalent language-neutral rule is that scanning stops at the last blank line before the first non-blank, non-// line in the file.)

  2. Andrew Gerrand

    I believe the language neutral rule also applies to Go source files, so if your copyright notice is inside a /* */ comment and includes blank lines, you’ll need to put // +build comments above the copyright notice.

Comments are closed.