DEV Community

Cover image for Golang
ayeolakenny
ayeolakenny

Posted on • Edited on

Golang

#go

Part 1

Introduction
Golang also known as GO is an open source computer programming language created by Google, it was developed at Google in 2007 by Robert Griesemer, Rob Pike and Ken Thompson, and was officially released and introduced to the public in 2009.
Golang Developers

From the left: Robert Griesemer, Rob Pike and Ken Thompson

What Is Golang
Golang is a general purpose programming language, making it useful in a wide range of areas, varying from web apps, network servers, mobile apps and machine learning, just to mention a few.
Golang is a statically typed and compiled programming language like the C family.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")
}
Enter fullscreen mode Exit fullscreen mode
//Result
Hello, playground
Enter fullscreen mode Exit fullscreen mode

Run in Playground

Golang comes with some amazing features like memory safety, garbage collection, structural typing and concurrency, which I would go through as we move further in this article.
However the Golang programming language is engineered for building larger scale and complex software, projects that involves distributed networks, cloud services and other backend technologies, it can also be very useful in solving problems encountered in complex software infrastructure as you scale.

Some Major Features Of Golang

  • Compiled Programming Language: Golang generates binaries for your applications, complete with dependencies, no iinterpreters or run-time installations are required. In simple terms Golang generates machine code directly from the source code and not from interpreters, in this case no pre-runtime translation takes place, making it a very fast programming language. Golang Image
  • Error Handling: Golang is a statically typed programming language, that supports type safety, errors are caught by the compiler before execution. Go codifies errors with the built-in error interface:
type error interface {
    Error() string
}
Enter fullscreen mode Exit fullscreen mode
//Result
can't load package: package main: 
prog.go:1:1: expected 'package', found 'type'
Enter fullscreen mode Exit fullscreen mode

Run in Playgroung

Error values are used just like any other value.

func doSomething() error

err := doSomething()
if err != nil {
    log.Println("An error occurred:", err)
}  
Enter fullscreen mode Exit fullscreen mode
//Result
can't load package: package main: 
prog.go:1:1: expected 'package', found 'func'
Enter fullscreen mode Exit fullscreen mode

Run in Playground

  • Garbage collection: This is one of the exciting features of Golang, havr you ever thought of how messages are pushed in real-time that fast? Low latency garbage collection plays an important role in this. In simple terms garbage collection is the process of freeing memory space that is not being used, this process happens in a concurrent way while the program is running and not before or after execution of the program. Concurrency would be explained as we go further into the article. Read more on implementing memory management with Golang’s garbage collector here
  • Multi-Paradigm: Golang supports multiple programming paradigms including, Object Oriented Programming(OOP) without inheritance and functional programming. Golang Image
  • Concurrency: Basically this is simply the ability of the program to do multiple things at the same time, which allows it to handle numerous task at once in a given period of time. Golang has a very good support for concurrency using goroutines and channels.
  • Goroutines: A goroutine is a function or method that is capable of running concurrently with other functions or methods.
package main

import (
    "fmt"
    "time"
)

func print() {
    fmt.Println("Printing from goroutine")
}

func main() {
    go print()
    time.Sleep(1 * time.Second)
    fmt.Println("Printing from main")
}
Enter fullscreen mode Exit fullscreen mode
//Result
Printing from goroutine
Printing from main
Enter fullscreen mode Exit fullscreen mode

Run in Playground

From the code snippet above, we have a function print which is just printing a string, in the main function, we have called this function concurrently by using go as a prefix. So now we have 2 goroutines, first our main function and second our print function. We made the main goroutine to sleep for 1 second so that go print() has enough time to execute before the main groutine terminates, then the program will be terminated and no goroutine will run.
You can try this program by commenting go print().

//Result
Printing from main
Enter fullscreen mode Exit fullscreen mode

Run in Playground

  • Channels: In the goroutine code snippet above we used time.sleep to see the difference between how goroutine works, however a better way to do this is by using channels, goroutine actually communicates with each other by channels.
package main

import (
    "fmt"
)

func print(ch chan bool) {
    fmt.Println("Printing from goroutine")
    ch <- true
}

func main() {
    ch := make(chan bool)
    go print(ch)
    <-ch
    fmt.Println("Printing from main")
}
Enter fullscreen mode Exit fullscreen mode
//Result
Printing from goroutine
Printing from main
Enter fullscreen mode Exit fullscreen mode

Run on Playground

From the code snippet above, we defined a channel ch on line 13 and on line 14 we call print goroutine passing channel as argument. Our print function receives this channels, prints the Printing from goroutine and writes true to the channel. When this write is complete, the main goroutine receives the data from the ch channel, till this time our main goroutine was blocked and once it read data from the channel ch, it is unblocked and then the text Printing from main is printed.
Read more about concurrency here

Note: Concurrency is a property of a program where two or more tasks can be in progress simultaneously. Parallelism is a run-time property where two or more tasks are being executed simultaneously. Through concurrency you want to define a proper structure to your program. Concurrency can use parallelism for getting its job done but remember parallelism is not the ultimate goal of concurrency.

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. — Rob Pike

Some Drawbacks Of Golang:

  • Less Flexibility: Golang has less flexibility than in dynamically typed languages, static typed programming languages like Golang types are checked before runtime while dynamic typed programming languages like JavaSript are checked on the fly during execution.
package main

import (
    "fmt"
)

func main() {
    m := "6"
    n := 6

    fmt.Println(m + n)
}
Enter fullscreen mode Exit fullscreen mode
//Result
./prog.go:11:19: invalid operation: m + n (mismatched types string and int)
Enter fullscreen mode Exit fullscreen mode

Run in Playground

In the code snippet above, statically typed languages like Golang would throw an error because they don't allow for type coercion.

function main(){
  var m = "6";
  var n = 6;

  console.log(m + n);
}

main();
Enter fullscreen mode Exit fullscreen mode
//Result
66
Enter fullscreen mode Exit fullscreen mode

Run in Sandbox

In the code snippet above, dynamically typed languages like JavaSript would merge the string and the number together.

  • Smaller Number Of Packages: As compared to other ecosystem like Node.js. This is because Golang's standard is full of features which mostly doesn't need third-party support. However, the number of packages are increasing.

In conclusion here are some real world examples of tools and software that uses Golang:

  • Kubernates: The Google-backed container platform.
  • Drop-box: The cloud storage and file sharing.
  • Cloudfare: A content delivery network, DDoS mitigation ans internet security service.
  • Malware bytes: An antivirus software.

Part 2

Installation

Windows

Installation Of Golang on Windows OS:

  • You’ll be completing most of the installation and setup on a command-line interface, which is a non-graphical way to interact with your computer. Make sure you have an internet connection and administrative access.
cd ..
Enter fullscreen mode Exit fullscreen mode

Switch to your home directory, for example C:\Users\kenny

  • Navigate to the Go installation website here. Download and install the latest 64-bit Go set for Microsoft Windows OS.
  • After the installation, run the Command Prompt on your computer go version. You should see something similar to this on your command prompt:
Microsoft Windows [Version 10.0.16299.15]
(c) 2017 Microsoft Corporation. All rights reserved.
c:\Users\kenny>go version
go version go1.10 windows/amd64
Enter fullscreen mode Exit fullscreen mode
  • Create your work-space, confirm your Go binaries by going to your computer’s Control Panel, then to System and Security > System > Advanced system settings, and on the left-hand pane click the Advanced tab. Then click on Environmental Variables on the bottom-right-hand side. Ensure Path under System Variables has the “C:\Go\bin” variable in it. Then create your Go work-space. This will be in a separate and new folder from where the Go installation files are saved. For example, your G installation files were saved under the path C:\Go and you are creating your Go work-space under C:\Projects\Go In your new Go work-space folder, set up three new folders:

Folder Creation

  • Create the GOPATH variable and reference your newly-created Go work-space. Go back to your Control Panel and navigate to System and then Environmental Variables. Then under System Variables click on New. Next to Variable Name, enter GOPATH, and next to Variable Value enter C:\Projects\Go. File path
Microsoft Windows [Version 10.0.16299.15]
(c) 2017 Microsoft Corporation. All rights reserved.
c:\Users\kenny>echo %GOPATH%
Enter fullscreen mode Exit fullscreen mode
Check that your path has been set correctly, by entering "echo %GOPATH%" on the command line.
  • Verify that all is working correctly by opening the command line and typing: go get github.com/golang/example/hello Wait for the code to be entirely implemented (this could take a few seconds), then enter in the following in the command line: %GOPATH%/bin/hello If the installation was successful, you should get the following return message: Hello, Go examples!.
c:Users\kenny>go get github.com/golang/example/hello
c:Users\kenny>%GOPATH%/bin/hello
Hello, Go examples!
c:\Users\kenny>
Enter fullscreen mode Exit fullscreen mode

I hope the installation was successful. And if you run into any errors or confusing messages. You can reference here.
Congrats you are now ready to develop in Golang.

Installation Of Golang on a Mac OS:

  • To download the latest Go release visit here. You will see the download link for Apple macOS. The current version of Go 1.13 support macOS 10.10 or later versions with 64-bit support only. Alternatively, you can download Go 1.13.3 using the curl command line.
$ curl -o golang.pkg https://dl.google.com/go/go1.13.3.darwin-amd64.pkg
Enter fullscreen mode Exit fullscreen mode
  • You have downloaded the Go package on your macOS system. To install it simply double click on the downloaded file to start the installation wizard. Command-line users can execute the below command to start the installation.
$ sudo open golang.pkg
Enter fullscreen mode Exit fullscreen mode

Follow the installation wizard and complete the installation process.

  • Edit the ~/.bash_profile or ~/.profile file (or its equivalent) to set environment variables. Commonly you need to set 3 environment variables as GOROOT, GOPATH and PATH. GOROOT is the location where Go package is installed on your system.
$ export GOROOT=/usr/local/go
Enter fullscreen mode Exit fullscreen mode

GOPATH is the location of your work directory. For example my project directory is ~/Projects/Proj1.

$ export GOPATH=$HOME/Projects/Proj1
Enter fullscreen mode Exit fullscreen mode

Now set the PATH variable to access go binary system wide.

$ export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
Enter fullscreen mode Exit fullscreen mode
  • The govendor is a tool used for managing the Go application dependencies efficiently. You should consider this to install on your system.
go get -u github.com/kardianos/govendor
Enter fullscreen mode Exit fullscreen mode
  • Finally, you have successfully installed and configured go language on your system. First, use the following command to check the installed Go version.
$ go version

go version go1.13.3 darwin/amd64
Enter fullscreen mode Exit fullscreen mode

I hope the installation was successful. And if you run into any errors or confusing messages. You can reference here.
Congrats you are now ready to develop in Golang.

Installation Of Golang on Linux OS:

  • Go here and download the latest version of GoLang in an archive file as follows:
$ cd ~/Downloads
$ wget -c https://storage.googleapis.com/golang/go1.7.3.linux-amd64.tar.gz
Enter fullscreen mode Exit fullscreen mode
  • Next, check the integrity of the tarball by verifying the SHA256 checksum of the archive file here using the shasum command as below, where the flag -a is used to specify the algorithm to be used:
$ shasum -a 256 go1.7.3.linux-amd64.tar.gz

ead40e884ad4d6512bcf7b3c7420dd7fa4a96140  go1.7.3.linux-amd64.tar.gz
Enter fullscreen mode Exit fullscreen mode

To show that the contents of the downloaded archive file are the exact copy provided on the GoLang website, the 256-bit hash value generated from the command above as seen in the output should be the same as that provided along with the download link.

If that is the case, proceed to the next step, otherwise download a new tarball and run the check again.

  • Then extract the tar archive files into /usr/local directory using the command below.
$ sudo tar -C /usr/local -xvzf go1.7.3.linux-amd64.tar.gz
Enter fullscreen mode Exit fullscreen mode

Where, -C specifies the destination directory..
Configure your environment, first, setup your Go workspace by creating a directory ~/go_projects which is the root of your workspace. The workspace is made of three directories namely:

  • bin which will contain Go executable binaries.
  • src which will store your source files and
  • pkg which will store package objects. Therefore create the above directory tree as follows:
$ mkdir -p ~/go_projects/{bin,src,pkg}
$ cd ~/go_projects
$ ls
Enter fullscreen mode Exit fullscreen mode
  • Now it’s time to execute Go like the rest of Linux programs without specifying its absolute path, its installation directory must be stored as one of the values of $PATH environment variable. Now, add /usr/local/go/bin to the PATH environment variable by inserting the line below in your /etc/profile file for a system-wide installation or $HOME/.profile or $HOME./bash_profile for user specific installation: Using your preferred editor, open the appropriate user profile file as per your distribution and add the line below, save the file and exit:
export  PATH=$PATH:/usr/local/go/bin
Enter fullscreen mode Exit fullscreen mode
  • Then, set the values of GOPATH and GOBIN Go environment variables in your user profile file (~/.profile or ~/bash_profile) to point to your workspace directory.
export GOPATH="$HOME/go_projects"
export GOBIN="$GOPATH/bin"
Enter fullscreen mode Exit fullscreen mode

Note: If you installed GoLang in a custom directory other than the default (/usr/local/), you must specify that directory as the value of GOROOT variable.
For instance, if you have installed GoLang in home directory, add the lines below to your $HOME/.profile or $HOME/.bash_profile file.

export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin
Enter fullscreen mode Exit fullscreen mode
  • The final step under this section is to effect the changes made to the user profile in the current bash session like so:
$ source ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

OR

$ source ~/.profile
Enter fullscreen mode Exit fullscreen mode
  • Finally time to verify the installation, Run the commands below to view your Go version and environment:
$ go version
$ go env
Enter fullscreen mode Exit fullscreen mode
  • To test your if your Go installation is working correctly, write a small Go hello world program, save the file in ~/go_projects/src/hello/ directory. All your GoLang source files must end with the .go extension. Begin by creating the hello project directory under ~/go_projects/src/:
$ mkdir -p ~/go_projects/src/hello
Enter fullscreen mode Exit fullscreen mode

Then use your favorite editor to create the hello.go file:

$ vi ~/go_projects/src/hello/hello.go
Enter fullscreen mode Exit fullscreen mode

Add the lines below in the file, save it and exit:

package main 

import "fmt"

func main() {
    fmt.Printf("Hello, you have successfully installed GoLang in Linux\n")
}
Enter fullscreen mode Exit fullscreen mode
  • Now, compile the program above as using go install and run it:
$ go install $GOPATH/src/hello/hello.go
$ $GOBIN/hello
Enter fullscreen mode Exit fullscreen mode
  • To run your Go binary executables like other Linux commands, add $GOBIN to your $PATH environment variable. I hope the installation was successful. And if you run into any errors or confusing messages. You can reference here. Congrats you are now ready to develop in Golang.

Go image

Top comments (0)