1. Mod file
It has module name, which is either name of the project or name of the module/package. It should be coherent to the code hosting repo, like GitHub. It has list of all the external dependencies.
CLI command - go mod init github.com/adexh/golang
go mod get
β Gets the module from GitHub
go mod download
β uses the mod file to download all the modules
2. Main package
This is the entry point. An executable must have a main.go
file, with package main
declared, and the main function.
3. Go Build
Go build is powerful, it builds to code into executable file as per the OS. It can also build an executable for other OS, is any host OS. Like in MacOS you can build .exe file, and vice-versa.
GOOS=windows GOARCH=amd64 go build .
4. Imports
Importβs last word in the hierarchy will be used to access it β import "math/rand"
then, β rand
will be used to access the package
5. Packages
Package name should be as short as possible, to ease out the import. Package name is by convention the folder name. If a package is imported, its variables, functions, etc. are not accessible if they are in small case. Its also Go way to handle encapsulation.
6. Functions
Syntax -
func add(x int, y int) int {
return x + y
}
// Go can return multiple values
func swap(x int, y int) (int, int) {
return y, x
}
// A way in go to initialize in return type, but its hard to read and track
func split(sum int) (x int, y int) {
// Not required to initialize the x and y, as they are implicitly initialized as zero values in the return type declaration
x = sum * (4/9)
y = sum - x
return // Here x and y will be returned automatically
}
go is statically typed, needs to declare types of the parameters passed, and the return type from the function.
7. Variables
7.1 Declaration
Variables can be declared in 3-ways
var i int // β This can be declared inside or outside of a functions. Variable is initialized with the zero state of the type.
var i int = 1 // β This is declaration plus initialization
func test() {
i := 0 // β This is declaration plus initialization short hand way, but can be used only inside a function
}