Golang
ayeolakenny
Posted on November 14, 2019
Part 1
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")
}
//Result
Hello, 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.
- 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
}
//Result
can't load package: package main:
prog.go:1:1: expected 'package', found 'type'
Error values are used just like any other value.
func doSomething() error
err := doSomething()
if err != nil {
log.Println("An error occurred:", err)
}
//Result
can't load package: package main:
prog.go:1:1: expected 'package', found 'func'
- 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.
- 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")
}
//Result
Printing from goroutine
Printing from main
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
- 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")
}
//Result
Printing from goroutine
Printing from main
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)
}
//Result
./prog.go:11:19: invalid operation: m + n (mismatched types string and int)
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();
//Result
66
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
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 ..
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
- 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 pathC:\Go
and you are creating your Go work-space underC:\Projects\Go
In your new Go work-space folder, set up three new folders:
- 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 enterC:\Projects\Go
.
- 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>
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
- 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
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 asGOROOT
,GOPATH
andPATH
.GOROOT
is the location where Go package is installed on your system.
$ export GOROOT=/usr/local/go
GOPATH
is the location of your work directory. For example my project directory is ~/Projects/Proj1
.
$ export GOPATH=$HOME/Projects/Proj1
Now set the PATH
variable to access go binary system wide.
$ export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
- 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
- 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
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
- 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
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
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
- 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 thePATH
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
- Then, set the values of
GOPATH
andGOBIN
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"
Note: If you installed GoLang in a custom directory other than the default (
/usr/local/
), you must specify that directory as the value ofGOROOT
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
- 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
OR
$ source ~/.profile
- Finally time to verify the installation, Run the commands below to view your Go version and environment:
$ go version
$ go env
- 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
Then use your favorite editor to create the hello.go
file:
$ vi ~/go_projects/src/hello/hello.go
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")
}
- Now, compile the program above as using go install and run it:
$ go install $GOPATH/src/hello/hello.go
$ $GOBIN/hello
- 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.
Posted on November 14, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.