golang引用结构在另一个文件的同一个包中

Chr*_* G. 8 go

main.go

LIB/file_1.go

...
package lib
...
type MyStruct struct{
}
....
Run Code Online (Sandbox Code Playgroud)

如何在同一个包/文件夹中的另一个文件中引用"MyStruct"?

我得到了未定义:MyStruct在构建lib/file_2.go时.我可以运行go install而没有错误,我应该忽略构建错误吗?

LIB/file_2.go

...
package lib
...
{
m MyStruct
}
....
Run Code Online (Sandbox Code Playgroud)

谢谢

Emd*_*won 11

这个命令对我有用

go run *.go
Run Code Online (Sandbox Code Playgroud)

实际上这将编译所有go文件并运行你的main函数.所以这很好用

  • 不要这样做。使用 `go build` 和 `go install`,它们存在是有原因的。特别是,如果你有 *_test.go 文件(你应该有!),使用 `go run *.go` 将会失败,并且它会默默地忽略 `// +build` 约束,这会导致它失败或行为意外的方式取决于构建标记的使用方式。 (2认同)

Wes*_*sie 6

你要求go工具编译lib/file_1.go,你永远不会提到lib/file_2.go它应该怎么知道它应该编译它?

来自go help build:

Build compiles the packages named by the import paths,
along with their dependencies, but it does not install the results.

If the arguments are a list of .go files, build treats them as a list
of source files specifying a single package.
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,您可以执行“go build file_1.go file_2.go” (2认同)

Von*_*onC 5

您应该可以MyStruct直接使用它,因为它和它的定义在同一包中。

如果您有任何问题,有时创建之前可以帮忙(例如,对于SublimeText + GoSublime这样的IDE )。 这样,便会被编译并显示在中,并且在编译期间可以使用定义。go install lib/file_2.go
lib/file_1.goGOPATH/pkglib/file_1.golib/file_2.go