What is the purpose of the commented import statement after the package statement?

Viewed 192

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.

1 Answers

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.

Related