Modules & Packages
Packages
Every Go application needs at least one package, that you can split your code in.
Usually you will have a default package main. Theoretically it could be any package name, as long as all files belong to the same package.
main is a special name for Go that tells it that this package will be the main entrypoint of the application.
In developing environments when executing the application with
go run app.goyou specify which file will be the entrypoint.But for production environments, where the code is compiled to be runned, everything will be mixed together in the binary file, so the entrypoint from the package name is important.
Compiling a project without a main package produces no executable file.
You may also split your code into multiple packages.
Importing own packages
// Your own packages
import "your-module/package-name"
// Third-party that were downloaded with `go get`
import "https://package-url.com"Variables, constants, functions, etc, are ONLY available (exported) to other packages if they start in Uppercase.
Ex.:
GetSomething(): this function will be available in other packages.getSomething(): this function is "private" to the package that it is declared.
Add packages locally
This downloads the package and stores globally on your system.
go get https://package-url.comInstall packages
Just like npm install run bellow to install the projects dependencies.
go getgo get -uModules
A module consist of multiple packages, and it is the go.mod file in your project.
Initiate the module in your project, or else, you will not be able to compile your project.
go mod init <path>The path can be a name or dummy URL, or even a github repository URL.
Last updated