Go concepts
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#.
Opposed to the statically typed, there are dynamically typed languages: Python, Ruby, JavaScript. In a dynamically typed language, it is possible to define a variable and assign a value of one type to it and then immidiately after that assign a value of a different type to that same variable.
var name = 123
name = "smth"
Short assignment
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: src
, bin
, pkg
.
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 namedmain
. A binary is created after building this package. Packagemain
must contain a function calledmain
,library
, the packages with names other thatmain
. Binaries are not created after building these packages. Go program execution always starts frommain
function.
Array vs Slice
An 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.
stackoverflow
unsafe package documentation
rune type
Is an alias of int32
, it represents a Unicode code point.
Go documentation
Generate random number
Given some int n, generate a random number within it. In order to do this:
- get a seed as a unique
int64
number from the current Unix timestamp, - create a
Source
of randomness based on the obtained seed, - create a
Rand
object based on theSource
of randomness, - get a random number from range starting from 0 to the given
n
using theRand.Intn
function.
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
randomNumber := r.Intn(n)