Tuesday, March 14, 2017

Getting Started with Golang Part 1: Overview of Language Features

Golang is a programming language with a strong focus on simplicity, performance, concurrency, readability, and utility. Golang is pre-compiled rather than JIT-compiled, has an extremely fast garbage collector (with sub-millisecond pauses), has a large standard library (including most popular crypto algorithms, a TLS implementation, and HTTP), and has many integrated tools which help with coding.

Language Features
There are a lot of features of Go, so I picked two of my favorites:
Goroutines (Concurrency)
Golang makes concurrency easy to implement - you can start a Goroutine almost the same way you would call a function - just putting it after the go keyword. For example:

go ExampleFunc(arg1,arg2)

That will run ExampleFunc on a new goroutine. Goroutines are extremely lightweight - using segmented stacks that grow and shrink as you append and remove data. So, you can use a large number of goroutines without using very much RAM. Instead of using system threads, they are put in a shared pool and instead a fixed number of system threads is used to run them. Go uses asynchronous syscalls, which allows it to run another goroutine while it is waiting for an operation to complete.
Easy Passing of Data In Multithreaded Code with Channels
Go uses the idea of thread communication by sharing data. You can create a channel, pass it to goroutines on creation and then use it for sending data between. Channels are statically typed.

If you want to use channels you first make a channel. Then you can write a value to a channel such as:
exampleChannel <- 1
The goroutine sending to the channel will block until something reads from the goroutine. You can have multiple goroutines listening to the same channel - which will load-balance the processing of the data from the channel between the goroutines. I used this technique in my small web crawler. You can also serialize data from a channel on one server and deserialize it to a channel on another server.
Standard Library
The Go standard library is filled with many commonly used utilities such as crypto (AES, RSA, ECDSA, SHA256/512, etc.). It has reflected encoding libraries - which will take any type (e.g. a struct) and encode it in your preferred encoding (XML/JSON/GOB). The standard library also includes various popular compression algorithms (bzip2, gzip, DEFLATE, zlib, and LZW). The standard library also has image encoders/decoders for popular formats (GIF, JPEG, PNG, and TIFF in experimental). Most importantly, it implements an HTTP(S) library (server & client) which is quick and easy to use.

No comments:

Post a Comment