Go Learn Golang! Introduction for Beginners

Go

Hi, my name is Andrey Grehov and welcome to “Learn Go Programming Language From Scratch”.

Golang Gopher by Olga Shalakhina

This series of articles is going to be a short course to get you comfortable programming Go. Go, also commonly referred to as golang, is a programming language developed at Google. It is a statically-typed language with syntax loosely derived from that of C. However, it is a new language across the board. In every respect the language was designed by thinking about what programmers do and how to make programming, at least the kind of programming we do, more effective, which means more fun. We’re going to go through all of the core features, focusing first on regular syntax, the essential task of creating variables and functions, basic program flow, and how these things are different here. Go rethinks the traditional Object Oriented development you might be used to while still providing an efficient means for code reuse, so we’ll look how Go does objects, polymorphism and inheritance.

We’ll cover some of the rules and principles that guide Go and how to make these more memorable so that it becomes natural to write.

I have to mention that this is my first ever blog post and my English is not perfect. I’ll do my best to write clear and meaningful posts.

What You Should Know before Learning Go

I would like to begin with a couple of assumptions about you, dear reader. To make the most of our time, this is all about Go. It’s not a beginner’s guide to programming. So at a minimum, you should already be comfortable with the fundamentals. Such as variables, loops, conditions, functions, basically the core concepts found in all programming languages. While Go is not exactly an object-oriented programming language, it would be more effective if you know at least the basic principles of object oriented programming. Terms like class versus object, inheritance, methods, and properties.

I will say it’s going to be helpful if you have at least a passing familiarity with any C-style language. Whether that’s C, Java, JavaScript, C Sharp, C++, PHP etcetera etcetera. You don’t have to be an expert, I just hope you don’t run screaming from the room if you see a pair of curly braces in your code. You see, as a new language, Go doesn’t try to be different just for the sake of being different. It openly takes ideas and syntax from the most popular languages such as Java, C++, C#, which in turn have been the inspiration for Objective C, Python, Ruby, Javascript, Scala, PHP, Perl… a veritable list of nearly all popular languages in use today. So It has a syntax that’s intentionally designed to be kind of familiar. But Go is different, even though it still looks kinda-C. It isn’t. It’s not C++, nor Objective C, and it doesn’t try to be.

And if you try and write Go as if you’re writing C you’re going to have a bad time. Now this is of course true when comparing Go to any other language. We want to enjoy the similarities when we find them, but just because you find three things in Go that seem almost identical to your current language, doesn’t mean the next three things will be. So, whatever language you know, try to leave most of the specifics behind and just bring the core concepts and ideas of programming with you.

Getting Started with Golang

Golang Gopher by Olga Shalakhina

Now let’s talk a little bit more about the language itself. First of all, it’s worth to mention that the Go programming language is an open source project. It’s a compiled, concurrent, garbage-collected, statically typed language developed at Google. The goals of the Golang project were to eliminate the slowness and clumsiness of software development and thereby to make the process more productive and scalable. Golang was designed by and for people who read, write, debug and maintain—large software systems.

And that is the only reason why Golang was created – simply out of the frustration of dealing with the complexity generated by very large teams of people working on very large pieces of software written in languages with large feature sets. While it has great features like compilation speed or easy concurrency, the main feature that makes Golang special is its extreme simplicity. Go tries to reduce the complexity at Google’s large projects at all costs, and it does so by sacrificing things, sometimes even principles that you thought untouchable. Golang is not like Python or Ruby, which “allow” you to write understandable code. In Go you basically have no other choice.

To put it more graphically. Go is your friend, but not your friend at a party asking you to take a taxi back home, Go is your friend at an intervention telling you that he’s thrown all the alcohol out of the window. Go won’t let you abstract yourself in the foot. Go is clearly a labor of love, with decades of well thought out language design baked right to its core.

With that all being said, let’s move on to the next step and finally try the language out.

Installation

The first thing we are going to do is setting up our environment, so that we could write and execute our code. We will obviously need to install the language itself and there are couple ways to do this. Let’s open the official web site and click the Download Go link right on its front page. Here where we can pick a binary release suitable for our operating system. You can see that the latest stable version of Golang is 1.5.1. And it’s worth to mention, most likely this is the version of the language which we are going to use throughout the whole course. So if you opened a Download page and saw that the version is different, let’s say 1.5.3 or maybe even 1.6.0, it means that the newer version of Golang has already been released and, of course, you can download and install it very easily, but, if you find yourself in this situation, just for the sake of learning, I would strongly recommend to scroll down the page and find the same version of Golang, as the one we are going to use in here. The reason for that is because if you install any other version of the language, there is really no guarantee that the examples from our course will work exactly the same as we expect them to work.

So, since I’m on MacBook, I’m going to download Go for the OS X operating system. If you are on Windows or Linux machine, then, of course, you’d have to download the package corresponding your system. There is one more note I would like to make before jump into setting up the environment. The Download page has 3 types of packages:

  1. Installer
  2. Archive
  3. Source code

Using an installer is the most simple way to get the language up and running as fast as possible. That’s exactly what I’m going to use here. An archive type is a simple archive, which contains binary distribution of Go. It’s useful if you want to install the language to a custom location on your hard drive. Since Golang is an open-source project, there is a third type of a package, which is, well, a source code of the language itself. Most users do not need it, but it’s still useful if a binary distribution is not available for your combination of operating system and architecture. If this is the case, follow the instructions at https://golang.org/doc/install/source to manually compile the language.

Once again, I’m going to use Golang version 1.5.1.

If you are using an installer, the installation process is very simple and straightforward. You just download the package, run it and install as any other application. But if you feel that you still need some help, you can always go to a Getting Started page, which has all the information required on how to install Golang for the most popular operating systems.

Your First Program

The workspace is ready and it’s great time to write our first program to better understand how it all works together. I’m sure that I won’t surprise you if I tell you that our first program is going to be as simple as outputting the “Hello World” string to a screen.

I’m going to use a Sublime Text editor to write the code. Sublime has become kind like of a standard and I know that a lot of people like to use it, and so do I. It’s a simple, fast and easy-to-use editor. But since such things are definitely a personal choice and a matter of taste, you can use any IDE you prefer. Anyway, you can download Sublime Text at its official website. I also use GoSublime, which is a Go plugin for Sublime Text editor. It provides some really nice features, such as syntax check, code completion and so on. We are not going to talk about the plugin installation process. It’s very simple and straightforward, so I’ll leave this task to you.

Setting Up Development Environment

Now when you have Go installed on your computer, it’s time to set up development environment, so that we could easily write, test and execute our programs. The first thing we need to do is to check whether you have go command accessible system-wide. The easiest way to do this is by opening the Terminal app (or Command Prompt if you are using Windows) and then typing go command. If you see something like “Command not found”, then you probably installed the language either from an archive or a source code. In this case you must set the GOROOT environment variable to point to the directory in which Go was installed. For instance, In Unix-like operating systems you could set the environment variables in .bash_profile file. It would like something like this:

export GOROOT=$HOME/opt/go
export PATH=$PATH:$GOROOT/bin

You would probably have to adjust the values to match your own system. Just keep in mind that the GOROOT variable must be set only when installing Go to a custom location. If you used an installer and your system still doesn’t know anything about go command, try to restart your Terminal or Command Prompt application.

Alright. I hope you are all set and from now on we will assume that Go is installed, meaning that the bin directory is in the PATH environment variable. The second thing I would like to talk about is the go command itself. What is it? What does it do? Well, go is a tool for managing Golang source code. It’s a swiss knife in the world of Go and we are going to use it A LOT. It allows us to do such things as:

  • compiling and installing packages along with their dependencies
  • testing and even downloading remote packages
  • and of course, we will use this tool to run our programs.

The go tool is designed to work with open source code maintained in public repositories. Although you don’t have to publish your code anywhere and this is completely up to you. Now Golang code must be kept inside a workspace, which is, in turn, a specific directory hierarchy. It consists of three directories at its root: src, pkg and bin.

  • src contains Golang source files organized into packages. This is basically a place where we put all the source code of our future programs.
  • pkg contains package objects. We’ll take a first look at the basics of packages in a few minutes and then discuss them more deeply a little later.
  • bin folder contains Golang compiled binaries. To put it more simply – files that we will be able to execute.

Once again. All the Golang code must be kept inside a workspace. So! Let’s not spend too much time and just build the workspace as a first step. I’m going to create a new folder named gospace in the root of my home directory. If you are using Windows, you can create exactly the same folder at the root of disc C. And then, I’ll also create src, bin and pkg inside of gospace.

Great. We now have a basic structure of the Go workspace. By convention, all your Go code and the code you will import, will live inside a workspace. Even more, most Golang programmers keep all their Go source code and dependencies in a single workspace.

For the go tool to be able to build local programs and packages, we need to tell Go where the workspace is located. There is a GOPATH environment variable, which is responsible for that. So let’s give this variable the right value.

export GOPATH=$HOME/gospace I recommend to add this command to a.bash_profle file, so that we don’t have to set the variable every time we boot a computer. Also, add the bin folder from the workspace to a PATH environment variable, so that we could easily call the binaries we compile. You can put it anywhere within your .bash_profile file.

export PATH=$PATH:$GOPATH/bin Some of you may ask things like: “What all of these environment variable are, what do they really do?”. Well, let me try to explain it real quick. In short, environment variables describe the environment in which programs run in. This concept exists in most operating systems, from Linux to OS X to Windows. They are used by all kinds of programs and scripts to answer questions like: “What is the name of the computer where I am installed? What is the name of the user running me? What is my current working directory?”. And so on and so forth. As an example, PATH is one of the most popular environment variables. Many programs need to know where to find certain files, and the PATH variable tells them where they can find what they need. In our case, we’ve created a GOPATH variable to let the Go tools know where the workspace is. At the same time, we’ve added $GOPATH/bin to a PATH variable and from now on, all the executable files from this directory become something like a command in your terminal, similar to ls or mv. And by the way, ls and mv, and the rest of commands you usually run, are also part of the PATH variable. If we would initialize PATH variable with an empty value, our operating system wouldn’t know where to look for commands and at that point, running ls would result to something like No such file or directory. Let’s do a quick experiment just for the sake of learning.

I can run env to view all the existing variables. I’ll copy the PATH variable and its value, so that I can put it back later.

You can see, that after running export PATH=“”, my environment no longer knew anything about ls command. This is because PATH environment variable was empty, so the system didn’t know where to look for my commands. Once I set the right value for the PATH variable, ls command started to work as expected.

All of these is not exactly related to Golang, but this basic knowledge is pretty important in general. At least, you now have a better understanding of what an environment variables are and, what’s more important, the purpose of the GOPATH variable.

Now let’s launch Sublime and open the gospace workspace from there. The workspace is currently empty, we only have three folders in it – bin, pkg and src. There are no files yet. Let’s create one. But, since the workspace may eventually have a lot of applications, we somehow need to be able to differentiate them. So I’m going to create app.1 folder under the src directory. app.1 is kind of a root folder of our first application. Create a new file, let’s say hello.go, under app.1.

Every Go program is made up of packages and a typical program starts running in a package main. So we say:

package main All Go files start with declaring a package and I’m also going to import an external package. The one we’ll need in our application is called fmt.

import "fmt" The import statement allows you to use external code. The fmt package, which is provided by the standard library, allows you to format and print data. Now let’s create an entry-point of our application. When your Golang program is executed, the first function called will always be main(). You might be familiar with the same concept from C language. This is how it looks in Go:

func main() {
}

Now let’s try to print something. We’ll use the Printf function from the fmt package we imported before. Printf writes a formatted string to standard output, which is a terminal in our case. The complete source code of hello.go is gonna look like this:

package main
import "fmt"
func main() {
    fmt.Printf(“Hello, World!\n”);
}

Great! Our first program is ready and it’s time to compile and run it. The preferred way to build a Golang program is to use the go tool. Open the Terminal app. To build our application, let’s cd to the src/app.1 and run:

go build hello.go This command will produce a new file named hello. It’s an executable which was generated during the compilation process. We can run it by simply typing its name:

./hello You should see the Hello, World! string, meaning that the application performs without errors. Except one thing! The executable was created under the src folder of our application and this fact doesn’t really conform to the concept of Go workspace. The purpose of src folder is to keep source code files only. And, according to the folder’s name, it’s quite obvious, right? So, let’s delete the binary we just created and re-compile the application in a slightly more interesting fashion.

rm hello
go install app.1

Now if you run ls, you won’t see the executable in the current folder. There is the source file only and that’s exactly what we are interested in. Now where is the executable? Well, according to the idea of Go workspaces, there is a bin folder, which serves as a container for all the Golang compiled binaries. This is where the app.1 executable resides in.

Now we were compiling the application itself and not just a single file, so that’s why the binary is named app.1 – the same as our application name.

So when you install programs with go tool, it’ll automatically understand, whether you do so in the workspace or not.

There is last one important thing I would like to mention here.

Having the GOPATH environment variable pointing to our workspace, we can compile our applications from any place of the system. I can be in my home directory or even in the root of the file system. It doesn’t really matter. We’ll still be able to install the app.

Pretty much the same thing happens when we run programs. The bin directory from our workspace is part of the PATH environment variable. Thus I can easily run the application without actually being in the bin directory itself. At that, app.1 is just like another command of your operating system.

The Go Playground

We installed Go, set up the development environment and built a very simple application. I believe now it’s a good time to look just a little bit deeper into the language and learn the basics of Go. But, before we get started, I would like to show you a really nice tool which we are going to use throughout the next few articles.

Go authors have created a web application, that allows you to edit and run Golang code right from your web browser. It’s called the Go Playground and you can find it by navigating to play.golang.org.

As you can see, it’s basically an online code editor. We can type Go code there and execute it by clicking the Run button. Even more, the tool can re-format all the source code for you making it look more clean. It’s a handy tool and for now I’m going to use it just for the sake of demonstrating the basics of Go.

That’s it for today. This article is a cross-post from my original blog.

Comments