Go is a statically typed language
Meaning that a variable type must be known at compile time. When a variable is defined, a type is assigned to it. This type cannot be changed later in the program. In a given scope, only one variable can exist with a given name of a given type. Other statically typed languages: Java, C#.
var name = 123 name = "smth"
Inside a function, when declaring a variable and assigning a value to it, a short assignment statement
n := 3 can be used instead of
var n int = 3 containing
var keyword and the variable type
int. Outside a function, the
var keyword must always be used when declaring a variable.
GOPATH environment variable
GOPATH environment variable contains a colon separated string with a list of paths to search Go code in. It is used to import the listed in Go applications dependency packages.
GOPATH girectory has three child directories:
When using modules, GOPATH is no longer used for resolving imports. However, it is still used to store downloaded source code (in GOPATH/pkg/mod) and compiled commands (in GOPATH/bin).
More details on GOPATH: Go documentation
Go package types
There are two package types in Go:
executable, the package named
main. A binary is created after building this package. Package
mainmust contain a function called
library, the packages with names other that
main. Binaries are not created after building these packages. Go program execution always starts from
Array vs Slice
Array is a fixed length sequence of elements of a given type, while a
Slice is a variable length array.
uintptr vs unsafe.Pointer
uintptr is an integer type. It is an integer representation of a memory address. But it is not a live reference to memory blocks it is pointing to.
usafe.Pointer is a pointer type. It is a pointer to an arbitrary type.
unsafe package documentation
Is an alias of
int32, it represents a Unicode code point.
Generate random number
Given some int n, generate a random number within it. In order to do this:
- get a seed as a unique
int64number from the current Unix timestamp,
- create a
Sourceof randomness based on the obtained seed,
- create a
Randobject based on the
- get a random number from range starting from 0 to the given
source := rand.NewSource(time.Now().UnixNano()) r := rand.New(source) randomNumber := r.Intn(n)