This repo has 3 go files all begin with "package lumber".
To use this package, I'm supposed to put this in my GOROOT
and simply
import lumber
in my program. How do variables and types in this package connect with each other across multiple files? How does the go compiler know which file to begin reading first?
In case I want to read the package, where should I begin reading to understand the package? What exactly is the flow of things here?
A package can have many files but only one file with main function, since that file will be the entry point of the execution. If a package does not contain a file with main package declaration, then Go creates a package archive ( . a ) file inside pkg directory. Since, app is not an executable package, it created app.
Create New File In the above code, it is visible that this file is part of the main package as mentioned in the first line. We can import multiple packages to the same file as they need to be wrapped inside parenthesis as we do here for “fmt” & “time” packages.
Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs.
You can have multiple main function in go but the package should be declared main. This way you can have multiple go scripts/file inside package main where each file will have main function.
To elaborate on jnml's answer:
When you use import "foo/bar"
in your code, you are not referring to the source files (which will be located in $GOPATH/src/foo/bar/
).
Instead, you are referring to a compiled package file at $GOPATH/pkg/$GOOS_$GOARCH/foo/bar.a
. When you build your own code, and the compiler finds that the foo/bar
package has not yet been compiled (or is out of date), it will do this for you automatically.
It does this by collating* all the relevant source files in the $GOPATH/src/foo/bar
directory and building them into a single bar.a
file, which it installs in the pkg directory. Compilation then resumes with your own program.
This process is repeated for all imported packages, and packages imported by those as well, all the way down the dependency chain.
*) How the files are collated, depends on how the file itself is named and what kind of build tags are present inside it.
For a deeper understanding of how this works, refer to the build docs.
No, you're not "supposed to put this in my GOROOT". You're supposed to execute
$ go get github.com/jcelliott/lumber
which will clone the repository into $GOPATH/src/github.com/jcelliott/lumber
. Then you can use the package by importing it in your code as
import "github.com/jcelliott/lumber"
About the scoping rules: Declarations and scope
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