Golang Concepts – mapped with OS concepts

Golang has been developed with a lot of thinking about how developers like to develop. Hence, there are a lot of concepts and background reason for every decision made by them. We just need to go through the documentation to understand them.

I will be listing some of the sections that are worth the read :
– The go memory model: https://golang.org/ref/mem
The section on Synchronization talks about memory initialization, memoty handling in goroutines, channel communication and locks.

– Memory allocation with new & make:

– Concurrency:
Discussion about sharing via communcation, goroutines, channels, Parallelization

– Variable Declarations:
Outside a function, every statement begins with a keyword (var, func, and so on) and so the (Short Variable Declaration) := construct is not available. (https://tour.golang.org/basics/10)

– Types: All defines types and their alias defined. (https://tour.golang.org/basics/11)
bool string
int = int8(also byte) int16 int32(also rune) int64
uint = uint8 uint16 uint32 uint64 uintptr
float32 float64
complex64 complex128
The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
Zero values are the default values set for the types: 0, false, “”, nil

– Constants :
Constants are declared with const keyword and cannot be declared using the := syntax. Numeric constants are high-precision values.

– Type Conversion:
Unlike in C, in Go assignment between items of different type requires an explicit conversion. There is no auto conversion. (https://tour.golang.org/basics/13)

– FOR: It has three parts where 1st and 3rd are optional. Also, FOR is Go’s while after dropping semicolons and the 1st and 3rd condition.
There are no parentheses surrounding the three components of the for statement and the braces { } are always required. Same for IF statements.
At that point you can drop the semicolons: C’s while is spelled for in Go.

-IF: Like for, the if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if.

-Switch: Switch can also have a short assignment. Also, the value to be compared can be missing in which case, the Case can have a comparison which would return true/false
A case body breaks automatically, unless it ends with a fallthrough statement.

Pointers, Structs, Pointers to Structs,

Struct Literals(instance): You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)
Arrays: [n]T An array’s length is part of its type, so arrays cannot be resized. Printing an array without an index will print all values.

Slices: A slice is dynamically sized. A slice gives much more flexibility. Eg: arr[0:5] will give a slice of first 5 elements of an array. Slices are like reference to array. It changes the underlying structure of the array it references.
Slice Defaults – 0 for low bound and length for upper bound. The upper bound takes the (upper value -1)  (https://tour.golang.org/moretypes/10)
A slice has both a length and a capacity. It goes out of bounds if the length goes over capacity. (https://tour.golang.org/moretypes/11)
s = s[:2] => lower bound will take values from the current slice, Upper Bound takes value from the original slice. Zero value of slice is nil which has len = cap = 0 and no underlying array.  Slices of slices can also be made easily.
(More Usage and Internals: https://blog.golang.org/go-slices-usage-and-internals)

Make: Used to inititialize and allocate memory. Takes optional parameters. It takes type, length and cap. The make function returns a map of the given type, initialized and ready for use. (https://tour.golang.org/moretypes/13)

append: (https://tour.golang.org/moretypes/15)
range: For Iterating collections. When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.  And if you only want the index, drop the “, value” entirely. (https://tour.golang.org/moretypes/16)

Maps: If the top-level type is just a type name, you can omit it from the elements of the literal.  eg.  type Vertex struct {Lat, Long int64}
var m = map[string]Vertex{
“Bell Labs”: {40.68433, -74.39967},
“Google”:    {37.42202, -122.08408},
Map operations :
delete(m, key) , checking existence with  elem, ok = m[key]

Function Values: Functions are values too. and can be passed around like values. Function values may be used as function arguments and return values.  (https://tour.golang.org/moretypes/24)

Function closures: In Go, functions may be closures too. A closure is a function value that references variables from outside its body. Eg.
return func(x int) int {
sum += x
return sum

=========METHODS & INTERFACES========
A method differs from go as a method has a receiver defined. A method can be defined on a non-struct type as well. The receiver in such a case should be defined in the same package as the method.

Functions with a pointer argument must take a pointer while methods with pointer receivers take either a value or a pointer as the receiver when they are called. Also, methods with value receivers take either a value or a pointer as the receiver (https://tour.golang.org/methods/7) .
(to provide a pointer we use &<variable>). To define a pointer as an input, we mention var1 *type which specifies that the var1 is a reference to the pointer.

Interfaces: An interface type is defined as a set of method signatures. A value of interface type can hold any value that implements those methods. And it matters whether the receiver type that implements the interface is a struct or *struct. Interfaces are implemented implicitly. There is no explicit declaration of intent, no “implements” keyword.
Interface values : Under the covers, interface values can be thought of as a tuple of a value and a concrete type: (value, type). Use describe to find it. Note that an interface value that holds a nil concrete value is itself non-nil. (https://tour.golang.org/methods/11)
Empty Interface: The interface type that specifies zero methods is known as the empty interface. Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.

Type Assertions: A type assertion provides access to an interface value’s underlying concrete value.  t, ok := i.(T) .
Type Switch: This can be used in type switches wherever required.  switch v := i.(type)
Stringer:  Stringer is a interface type that can describe itself as a string. It has the String function declared. (https://tour.golang.org/methods/18)

Error: Errors are expressed by error interface type (similar to Stringer, error interface looks for Error() string function) (https://tour.golang.org/methods/20)

Readers: io. Reader interface is used for reading which has a Read function to read the end of stream of data.  (https://tour.golang.org/methods/21 https://tour.golang.org/methods/22). There are also ways in which a reader wraps another reader.
There are various implementation of it including files, network connections, compressors, ciphers, and others. (https://golang.org/search?q=Read#Global)

Images: Package image defines the Image interface:  ColorModel(), Bounds(),  At(x, y int) functions. The color.Color and color.Model types are also interfaces which have default implementations  like color.RGBA and color.RGBAModel.

Goroutines: Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives.

Channels: Channels are a typed conduit through which you can send and receive values with the channel operator, <-.  It is defined by chan and must be initialized using make (similar to slices, maps). By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.  (https://tour.golang.org/concurrency/2)

Buffered Channels: Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel. It sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

Closing a channel : Channel can be closed using close(ch) only by a Sender (and never a receiver ). Channels do not require to be closed. It is only necessary when the receiver needs to be told of that no more values are coming.

Select: Waiting on gorountine is achieved using this.  The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

Default Select: The default case in a select is run if no other case is ready.

Locks in GO: Locks can be achieved using sync.Mutex and its two methods Lock and Unlock (https://tour.golang.org/concurrency/9)
Useful Links: https://tour.golang.org/concurrency/11
The further reads from Go Blog:




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s