Go 101 Continued
The simplest Go program:
package main func main() { }The first line
package mainspecifies the package name (mainhere) of the containing source file.I just don’t understand this statement.
Let me go back to the other book I was reading (Go in action). There I found the following statement:
- For the build tools to produce an executable, the function
mainmust be declared, and it becomes the entry point for the program. - Function
mainis located in a package calledmain. If yourmainfunction doesn’t exist in packagemain, the build tools won’t produce an executable. - Packages define a unit of compiled code and their names help provide a level of indirection to the identifiers that are declared inside them, just like a namespace. This makes it possible to distinguish identifiers that are declared with exactly the same name in the different packages you import.
- For the build tools to produce an executable, the function
I am not sure if I understand the idea of packages in Go yet. What I think is happening is that the first line of a .go file declares its place in overall structure of the code.
Looking at chapter 3 of Go In Action, I find the following:
- All Go programs are organized into groups of files called packages.
- This is done so that code can be included in other projects as smaller reusable pieces.
- All .go files must declare the package that they belong to as the first line of the file excluding whitespace and comments.
- Packages are contained in a single directory. You may not have multiple packages in the same directory, nor may you split a package across multiple directories. This means that all .go files in a single directory must declare the same package name.
- The package name
maindesignates to the Go command that this package is intended to be compiled into a binary executable. All of the executable programs you build in Go must have a package calledmain.
Run Go Programs
- You can run a .go file by the command
go run simplest-go-program.go. This will compile your .go file and return any syntax errors encountered. - The
go runcommand is not the recommended way to compile large Go projects. For larger Go projects you need to run thego buildor thego installcommands. - Go project supporting Go modules needs a
go.modfile located in the root folder of that project. Thego.modfile can be generated by thego mod initsubcommand.
Some go Subcommands
go vet: checks code for possible logical errors.go fmt: formats Go source code with a consistent coding style.go test: runs tests and benchmarks.go doc: opens Go documentation in terminal windows.go mod init example.com/myproject: generates ago.modfile in the current directory. This turns the current directory into the root directory of a module calledexample.com/myproject.go mod tidy: adds missing module dependencies into and removes unused module dependencies from the go.mod file by analyzing all the source code of the current project.