Go generate 只扫描 main.go

标签 go go-generate

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




从项目目录的根目录运行 go generate 时,我在使用 go generate 生成 grpc 服务器时遇到了一些问题。

当我运行 go generate -v它只返回 main.go .但是,这些指令是在一个子包中定义的。如果我运行 go generate在子包中它按预期工作。我希望进口能够确保 go generate会找到子包并运行指令。

该项目具有以下结构:

cmd/
  root.go
  run.go
pkg/
  subpkg/
    protobuf/
      proto1.proto
    subpkg.go
main.go

subpkg.go 的内容
//go:generate protoc -I ./protobuf --go_out=plugins=grpc:./protobuf ./protobuf/proto1.proto
package subpkg


main.go 的内容:

package main

import (
    "fmt"
    "os"

    "my-project/cmd"
)

func main() {
    if err := cmd.RootCommand.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}


在 run.go 包中,我导入包 subpkg。

如何确保 go generate 可以从项目的根目录运行并执行所有子包中的所有指令。

最佳答案

您正在寻找 go generate ./... .

根据 go help generate :

usage: go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

...

For more about specifying packages, see 'go help packages'.
go help packages :
Many commands apply to a set of packages:

go action [packages]

Usually, [packages] is a list of import paths.

An import path that is a rooted path or that begins with
a . or .. element is interpreted as a file system path and
denotes the package in that directory.

Otherwise, the import path P denotes the package found in
the directory DIR/src/P for some DIR listed in the GOPATH
environment variable (For more details see: 'go help gopath').

If no import paths are given, the action applies to the
package in the current directory.

...

An import path is a pattern if it includes one or more "..." wildcards,
each of which can match any string, including the empty string and
strings containing slashes. Such a pattern expands to all package
directories found in the GOPATH trees with names matching the
patterns.

因此,当您没有为接受一个的 Go 命令指定一个包时,它假定该包是当前目录。子目录是不同的包,因此不包括在内。 “此包及其下子目录中的所有包递归地”的简写是./... ,如
go get ./...
go generate ./...
go test ./...

关于Go generate 只扫描 main.go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794748/

相关文章:

json - 在 golang 中解码 json

go - 如何停止被进程启动的外部 I/O 阻塞的 goroutine?

go - 如何阅读包文档

go - VPP插件可以用Go实现吗?

go - 如何关闭或清理标准输出管道?

golang protobuf 无法在泛型类型中解码