Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang reference struct in same package in another file

Tags:

How to reference MyStruct in another file in the same package or folder?

Currently I get undefined: MyStruct when go build lib/file_2.go. I can run go install with no error, should I just ignore the build error?

These are my files:

lib/file_1.go

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

lib/file_2.go

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

Thanks

like image 766
Chris G. Avatar asked Dec 18 '14 14:12

Chris G.


People also ask

How do I use a struct from another file in go?

The struct name in another package must start with a capital letter so that it is public outside its package. If the struct name starts with lowercase then it will not be visible outside its package. To access a struct outside its package we need to import the package first which contains that struct.

Can't define receiver from another package in go?

You can only define methods on a type defined in that same package. Your DB type, in this case, is defined within your dbconfig package, so your entity package can't define methods on it. In this case, your options are to make GetContracts a function instead of a method and hand it the *dbconfig.

How do I export a struct in Golang?

Go export struct Struct names and fields starting with a small letter are visible only inside their package. We create a new Go module with the go mod init command. This is the project structure. The Name and Occupation fields of the User struct are exported, while the age field is not.

How do I import another package into go?

To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.


2 Answers

This command works for me

go run *.go 

Actually this will compile all go file and run your main function. So this works well

like image 50
Emdadul Sawon Avatar answered Nov 01 '22 02:11

Emdadul Sawon


You're asking the go tool to compile lib/file_1.go, you never mention lib/file_2.go so how is it supposed to know 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. 
like image 20
Wessie Avatar answered Nov 01 '22 02:11

Wessie