3

Some packages have a commented import statement just after the package statement. An example is visible here.

. . .
package truetype // import "github.com/golang/freetype/truetype"
. . .

It seam that this appears on a package inside a module. Not all files of the package have this comment.

What is the purpose of this comment ? Why is it there ?

I didn’t find anything about this in the go specification.

chmike
  • 20,922
  • 21
  • 83
  • 106
  • 1
    This defines under which import path the package must be imported. – Volker May 04 '21 at 14:21
  • Related: https://stackoverflow.com/q/37330303/13860 – Jonathan Hall May 04 '21 at 14:28
  • 1
    @blackgreen: But the fact that it can be confused with documentation is a great reason that I dislike Go's various comment-based tricks. – Jonathan Hall May 04 '21 at 14:28
  • @Volker It seam that this has become obsolete since we use go.mod. Can I thus ignore it ? Is it replaced by the module name in the go.mod file ? – chmike May 04 '21 at 14:32
  • 1
    @chmike: it is redundant now with `go.mod`, and no longer needed – JimB May 04 '21 at 14:53
  • It might be redundant if the given import path actually matches the one from go.mod but if not I do not know if your build will succeed. Did you try it out? – Volker May 04 '21 at 14:58

1 Answers1

3

This is for custom import paths.

See the import path checking documentation, and also this SO answer.

A package statement is said to have an "import comment" if it is immediately followed (before the next newline) by a comment of one of these two forms:

package math // import "path"
package math /* import "path" */

The go command will refuse to install a package with an import comment unless it is being referred to by that import path. In this way, import comments let package authors make sure the custom import path is used and not a direct path to the underlying code hosting site.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412