gogodoc

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


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?


Solution

  • 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.