在doc.go文件中链接到另一个包的最佳方法是什么?

huangapple go评论67阅读模式
英文:

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

问题

在编写doc.go文件中的包文档时,如果想要链接到另一个包中的文档,最好的方法是什么?不幸的是,在doc.go文件中,引用已导入包的常规方法是行不通的,因为不允许存在未使用的导入。

// 在 doc.go 文件中的 foo 包文档
// foo 使用 [bar.Bar] 类型来完成一些操作。
package foo

import "foo.com/jonathan/godoctest/bar" // 这里会出现未使用导入的错误

使用完全限定的路径是可行的,但不太易读:

// 在 doc.go 文件中的 foo 包文档
// foo 使用 [foo.com/jonathan/godoctest/bar.Bar] 类型来完成一些操作。
package foo

有没有解决方法?

英文:

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?

答案1

得分: 1

引用导入包中的标识符,可以使用名为_的变量(空白标识符)。

// 在 doc.go 文件中为包 foo 添加文档
// foo 使用 [bar.Bar] 类型来完成一些操作。
package foo

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

var _ bar.SomeType // 这里 bar.SomeType 是一个类型
var _ = bar.Value // 这里 bar.Value 是一个函数、变量、常量等

只需要对导入的包进行一次引用。上述代码展示了引用类型或值的不同方法。

英文:

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.

答案2

得分: 0

你可以使用下划线来强制导入:
所以,这段代码会出错:

package main

import "fmt"
import "log"

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

但是这段代码会正确编译:

package main

import "fmt"
import _ "log"

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

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!")
}

huangapple
  • 本文由 发表于 2023年6月28日 08:24:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76569339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定