Best way to link to another package in doc.go files

254 Views Asked by At

What's the best way to link to a doc in another package when writing package docs in a doc.go file? Unfortunately, the normal approach of referencing an imported package doesn't work in doc.go files since unused imports aren't allowed.

// Package foo docs in a doc.go file
// foo uses [bar.Bar] types for doing things.
package foo

import "foo.com/jonathan/godoctest/bar" // Unused import error here

Using a fully qualified path does work, but doesn't make for the most readable docs:

// Package foo docs in a doc.go file
// foo uses [foo.com/jonathan/godoctest/bar.Bar] types for doing things.
package foo

Any ideas for a workaround?

2

There are 2 best solutions below

0
thwd On BEST ANSWER

Reference an identifier in the imported package using a variable with the name _ (the blank identifier)

// Package foo docs in a doc.go file
// foo uses [bar.Bar] types for doing things.
package foo

import "foo.com/jonathan/godoctest/bar"

var _ bar.SomeType // where bar.SomeType is a type
var _ = bar.Value // where bar.Value is a func, var, constant, ...

Only one reference to the imported package is required. The above code shows the different approaches for referencing a type or a value.

0
Zlat On

You can force import using _: So, this code will be erroneous:

package main

import "fmt"
import "log"

func main() {
  fmt.Println("Hello world!")
}

But this one will be build correctly

package main

import "fmt"
import _"log"

func main() {
  fmt.Println("Hello world!")
}