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
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.
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.
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.
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.
This command works for me
go run *.go
Actually this will compile all go file and run your main function. So this works well
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With