Golang/Basics
Main function
package main import ( "fmt" "time" ) func main() { fmt.Println("Welcome", time.Now()) }
Go modules and custom packages
A Go Module is a collection of Go packages. Why do we need Go modules to create a custom package? The answer is the import path for the custom package we create is derived from the name of the go module. In addition to this, all the other third-party packages(such as source code from github) which our application uses will be present in the go.mod
file along with the version. This go.mod
file is created with go mod init <mymodule>
when we create a new module.
# in directory mymodule/ initialize a module <mymodule> go mod init mymodule $ cat go.mod module mymodule go 1.17
The mymodule
is the base path to import any package created inside this module.
Source files belonging to a package should be placed in separate folders of their own. It is a convention(requirment) in Go to name this folder with the same name as the package. Example structure:
mymodule -> # 'go mod init mymodule' |- main.go # -> package "main" |- tools |- helper.go # -> package "tools" as the folder name
To import tools package from main.go import this "mymodule/tools"
- Siliencers
are useful to silience errors during development:
- import a package before using it error "imported and not used"
- import a package just to make sure the initialization takes place even though we do not need to use any function or variable from the package
Silienced by using it
package main import ( "learnpackage/simpleinterest" ) var _ = simpleinterest.Calculate func main() { }
Silienced import
import ( _ "learnpackage/simpleinterest" )