Learn Golang as a Python Developer

Learning Go or Golang as a Python developer, programmer or software engineer is easier than you think.

While there are quite a lot of things to learn and get familiar with, there are many benefits and many common characteristics.

Why learn Go as a Python developer

I find Python to be a very powerful and useful programming language, having used it on a wide range of projects for an even wider range of tasks. From Platform Engineering automation to Machine Learning and Artificial Intelligence, to building User Interfaces and creating APIs as well as building entire websites and web applications. Python has served me well and will continue to do so.

However, there are reasons for learning a new language, and Go has filled a void for me, specifically when it comes to being able to distribute and share my applications both across platforms as well as being able to run compiled code. Which as we all know, is usually much faster than code that is merely interpreted.

So faster code that we can also distribute as a static binary. Let’s get started!

Getting started

The first obvious thing to get started is to make sure you have Go installed on your computer, or whichever machine you plan on doing the development on.

You could always opt for using an online editor or IDE, but being able to do everything on your own machine is probably better. It gives you a more rounded view on how to get the whole system ready and teaches you any of those missing pieces you may not otherwise be aware of.

How to Download Go

You can download Golang from the Go website over at https://golang.org/dl/

If you’re on a Mac, as I am, I would recommend using Homebrew to install and manage Go (and pretty much everything else..).

If so, just type brew install go, or brew upgrade go if you already have Go installed and want to make sure you’re on the newest, slickest version. I’m currently on version 1.14.

Using Go in an IDE/editor

VS Code has become my editor of choice over the past two or three years, you can get it here: https://code.visualstudio.com/

It’s lightweight, fast, and has access to absolutely loads of extensions to make it better in every way.

As a software engineer for many, many years, I have changed editors more times than I care to remember. So far, VS Code keeps me pretty happy.

Setting up VS Code and adding the Golang Extensions

Within VS Code, click on the Extensions icon on the left-hand bar, and type Go into the search bar.

If you install this extension, you will get all the primary benefits you need!

Let’s not waste any more time…

How to Start a Project

Go uses a thing called Go Modules to organise code, it’s a much better alternative to using Go’s $GOPATH madness of Go version < 0.13. If you are not familiar with it, that’s fine, you don’t need to be to complete this tutorial. We will completely avoid all the craziness of it today.

You can make sure you’re on a required version by typing in go version in the command-line. This should return a string saying something like:
go version go1.14 darwin/amd64.

Start by creating a working directory:

mkdir -p ~/src/mygoproject && cd $_

Now create a git repository and initiate the project:

git init -q
git remote add origin https://github.com/ao/mygoproject

Next, we get to initiate our project’s primary module. This is important if you ever want to import any additional local files or packages.

go mod init github.com/ao/mygoproject

This will create a file in our project root directory called go.mod, which will now contain the following code:

module github.com/ao/mygoproject

go 1.14

At this point, we can open our project in VS Code, which can easily be done by typing code . to load the current directory.

If your CLI complains saying it doesn’t know what the code keyword is, then you will need to add it. To do this, open VS Code and press cmd+shift+p, then type install, you will see the Install 'code' command in PATH, as below:

Once this is done, you will need to reload your terminal window for the $PATH variable to be updated.

Writing your first Go code

Create a file called main.go.

We will enter all our code in this file for the time being.

Every Go file starts with a package <packagename> file. Because this is the entry point, we will call it main.

package main

Every Go application starts with a reserved function name called main(). Functions are defined by the func keyword, this is equivalent to the def keyword in Python.

package main

func main() {
	// our entry function
}

At this point, we have the absolute bare essentials for our Go application. This does absolutely nothing yet, but we can execute it without any errors.

Running a Go project from the command-line

In Python, you would type python filename.py and it would execute that file.

In Go, you use the go keyword along with the command you would like to trigger. go run filename.go does the same thing and loads and runs the file you have specified.

To make things a little easier for us, when we start including additional files, we opt to execute our application by issuing a go run . instead. This will load all Go code within this project, look for the main() method and run it.

If we do this with the above code, it will exit without any errors. This is because we aren’t yet doing anything amazing.

Let’s add a regular print("Hello world"), like we would do in Python.

In Go, we use the fmt module to provide us with the ability to print to the screen.

Adjust your main.go file to add these relevant pieces:

package main

import "fmt"

func main() {
	// our entry function
	fmt.Println("Hello world")
}

If we run our project again, as we did before, we will now get the string rendered to the CLI:

go run .

# Hello world

Splitting code into Functions

Functions in Go work mostly the same as how they do in Python, with a few exceptions, such as input and return types.

In Python, we could write a function like this:

# Take in 2 variables and return the concatenated result
def my_function_name(var1, var2):
    return var1 + var2

# use this function
print(my_function_name(1, 2))

# prints: 3

To do the same in Go, we could do something like this:

// We need to define the variable types: (var1 int, var2 int)
// Also have to explicity declare the return type: int
func my_function_name(var1 int, var2 int) int {
    return var1 + var2
}

// use this function
fmt.Println( my_function_name(1, 2 ) )

// prints: 3

We can see that it’s quite a bit simpler in Python, as variables are implicit. However, in Go we have to explicitly declare the input and output types.

Quickstart to Variables

Python comes packed with a few very useful variable types, these can be summed up as:

Numbers, String, List, Tuple, Dictionary

While in Go, we have:

  1. Basic type: Numbers (integers, floats, complex), strings, and booleans
  2. Aggregate type: Array and structs
  3. Reference type: Pointers, slices, maps, functions, and channels
  4. Interface type

While things get a lot more complicated than this, it is good to know we have some options to compare to our Python commons.

How to Import Additional Files

Go version 1.11 introduced modules, and more recently it has been popularised as being ready for production.

This is great news, as beforehand, we would have to use the $GOPATH file structure to store all Go projects within one massive directory.

We created a module at the beginning of this tutorial and made sure to path it directly to our git repository, this was all on purpose!

Let’s add another file to our project, put some code in it and learn how to import and call it in our main.go file.

Create a directory called extras and a file in there called extrafile.go

In extrafile.go add the following code:

package extras

// The function name HAS TO start with a capital letter
// .. if you want it to be available outside this file
func HelloFromExtras() string {
	return "Hello From Extras!"
}

Note the package extras at the top, this is the same name as the directory this file is in. Regardless of what the filename is.

Now from our main.go file, we can include this package. This is how our main.go file looks once extras is imported:

package main

import (
	"fmt"
	"github.com/ao/mygoproject/extras"
)

func main() {
	// our entry function
	fmt.Println(extras.HelloFromExtras())
}

See how we have imported our additional package by its directory name off the back of the module we initialised our project as.

We have then printed out the HelloFromExtras method. We could also alias the package as follows if we wanted to use it under a different name. This is the case if our package happens to use a common or overridden name that already exists in our overall project somewhere else.

package main

import (
	"fmt"
	ourfile "github.com/ao/mygoproject/extras"
)

func main() {
	// our entry function
	fmt.Println(ourfile.HelloFromExtras())
}

If we run this from the CLI, using go run ., we should see:

go run .

# Hello From Extras!

The important things to remember here are:

  • Always use modules and module paths
  • Go doesn’t have public and private method types when sharing. Instead, capitalise the first letter of a method name if you want it to be public, otherwise keep it lowercase if you want it to be private, or only accessible by the same file.

func thisIsAPrivateMethod()

func ThisIsAPublicMethod()

Compiling your project

Python is an interpreted language, and as such you never need to worry about compiling any code. Simply write the code and use the python CLI to run it. Whether you do this using a Python Virtual Environment or achieve it some other way.

Golang code is so much faster than Python code because it is compiled down to static binaries. This means that it doesn’t require a virtual machine or runtime to execute. This is particularly useful if you are sharing your application with others who don’t have the source code.

You can use the build keyword from the CLI to build your binary:

Our project structure looks like this before we build:

Now we run go build . which will create an additional file for us:

Compiling Go projects is incredibly fast, especially if you’re coming from the C, C++, C# or Java world. As a Python developer, this may all be new to you. Don’t worry though, it’s not much more complicated than what you’ve just seen!

We’re now done and can execute our binary file from the CLI as we would expect to:

./mygoproject

# Hello From Extras!

Pushing to Github

At this stage, we have initialised our project and added a couple of different files to it.

However, we haven’t version controlled it yet.

We called the primary module github.com/ao/mygoproject and even added a git remote add origin https://github.com/ao/mygoproject at the start.

To push our code to Github, we need to make sure we have created the above repository and have performed a git add . (add whichever files you want to version), then a:
git commit -m "<your_message_name>"

Once this is done, simply run a git push origin master and you’re done!

Closing thoughts

While this tutorial touches on the getting started points of using Golang for Python developers, I will be writing many more advanced tutorials over the coming days and weeks.

If you are interested in learning how to use Golang as a professional software engineer and want to become an expert with the language, then consider joining the mailing list which is sent out once a week.

1 thought on “Learn Golang as a Python Developer”

  1. Pingback: Learn Golang as a Python Developer – Full-Stack Feed

Leave a Reply

Your email address will not be published.