Golang reference struct in the same package in another file

main.go

Library / file_1.go

...
package lib
...
type MyStruct struct{
}
....

How to link to "MyStruct" in another file in the same package / folder?

I get undefined: MyStruct when going build lib / file_2.go. I can run go install without errors, should I just ignore the build error?

Library / file_2.go

...
package lib
...
{
m MyStruct
}
....

thank

+4
source share
3 answers

You ask the go tool to compile lib/file_1.go, you never mention lib/file_2.go, and how should it know that it should compile it?

From 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.
+5
source

This command works for me.

go run *.go

In fact, this will compile the whole go file and run your main function. So it works well

+7

MyStruct , , .

If you have any problems, sometimes it can help (for an IDE, for example SublimeText + GoSublime , for example) to do go installbefore creating lib/file_2.go.
Thus, it compiles lib/file_1.goand is present in GOPATH/pkg, and the descriptions lib/file_1.govisible to lib/file_2.goare used during its compilation.

+3
source

Source: https://habr.com/ru/post/1568168/


All Articles