backgroundLayer 1Navigate back to the homepage

Learn Golang - Basics

Patryk Jeziorowski
December 23rd, 2019 · 5 min read

Introduction

Go is a modern programming language that is very simple and quick to learn. It makes full use of the power of today’s multicore computer processors, so your programs run very fast.

Over 10 years ago Google had a big problem - they had to maintain programs with millions of code. When they wanted to test a new change, they had to spend a lot of time compiling the code and turning it into a runnable process. It was a nightmare for developers and huge productivity loss.

To solve the issue, Google engineers Robert Griesemer, Rob Pike, and Ken Thompson sketched out some goals for a new language:

  • Fast compilation
  • Less cumbersome code
  • Unused memory freed automatically (garbage collection)
  • Easy-to-write software that does several operations simultaneously (concurrency)
  • Good support for processors with multiple cores

After years of work, Googe come up with Golang – a simple, productive language that is very fast to write, compile and run. Go went open-source in 2009 and is free to use for everyone now.

Golang is capable of writing web servers that handle multiple concurrent users connections at the same time. You can also create command-line tools for Window, macOS and Linux from the same source code. No matter what you are willing to do, Go will help you write more with less, simpler and easier to maintain code.

Run your first program

Go team has prepared an online environment for running simple Go programs on their servers. To run your first program:

  1. Go to https://play.golang.org/
  2. Click the Run button

You should see Hello, playground displayed at the bottom of the screen. Congratulations! You’ve just run your first Go app.

Let’s explain the code

It’s the time to explain what all the code means.

Each file in Go starts with a package clause. A package is just a collection of related code. The package clause determines to which package the code belongs to.

Next, most of Go files have a few import statements. Here you declare packages that you use so that your programs load a compile quickly. You don’t want to include everything in your program! Go compiler will not let you import packages that you don’t use, which is great!

Learn Golang Basics


The last part is the code which is usually split up into functions.

A function is a block of code that you can run from other places in your program. Similarly to Java, Go always look for the main function and runs that first, that’s why we called our function main.

As you can see in the playground, there is a Format button. When you click that button, Go compiler will adjust your code to the standard Go formatting. In Java, there are many disputes on styling conventions, and Go solves that problem with providing an official styling. That’s very nice!

One more interesting thing you may notice is the lack of semicolons. In fact, in Go they are optional – you may use them to separate the statements, but it’s not required and generally not advised to use.

Function that returns a value

If you execute the following code:

1package main
2
3import (
4 "math"
5)
6
7func main() {
8 math.Floor(3.14)
9}

You’ll notice that it does not print anything. This is because the math.Floor() function only returns a value, but nothing prints it.

The math.Floor() function takes a floating-point number, rounds it down to the nearest whole number, and returns that whole number.

To see the result of math.Floor(), we need to use the fmt.Println() function to print it to the screen:

1package main
2
3import (
4 "math"
5 "fmt"
6)
7
8func main() {
9 fmt.Println(math.Floor(3.14))
10}

Strings

In our first program, we used a string as an argument to Println. A string is a series of bytes that represent text. You can define strings directly within your code using string literals: a text in between double quotation marks like “Hello, playground”.

Runes

Go introduces a concept of Runes. While strings are used to represent a sequence of characters, runes are used to represent a single character.

If you want to use a Rune, you have to surround a character with single quotation marks like ‘A’. Go uses the Unicode standard for storing runes, so they can store any character on the earth.

Booleans

Bool value represents one of the two - true or false. They are very useful in conditional statements - similarly to all other programming languages.

Numbers

All you have to do is just to type a number. Golang treats integers and floating-point numbers as different types - a decimal point is used to determine if it’s an integer or float.

Types

Go is statically typed - the type of each variable is known at the compilation time. Functions expects arguments to be of a particular type. They also return values of previously defined type. If you use incorrect type, the Golang compiler will let you know even before you run the program.

Declaring variables

A variable is a piece of storage containing a value. You can give a variable a name by using a variable declaration.

Just use the var keyword followed by the name and type of the value:

1package main
2
3import (
4 "fmt"
5)
6
7func main() {
8 var myVariable int // var VARIABLE_NAME TYPE
9
10 myVariable = 25
11
12 fmt.Println(myVariable)
13}

You can also declare a variable and give it a value in the same line:

1package main
2
3import (
4 "fmt"
5)
6
7func main() {
8 var myVariable int = 25
9
10 fmt.Println(myVariable)
11}

You can assign a new value to an existing variable but it needs to be of the same type!

Learn Golang Basics

Zero values

If you don’t provide a value to the variable, it will contain Zero Value of its type.

For numeric types, zero value is 0. For bool, it’s false. For strings - an empty string.

Short variable declaration

If you know beforehand the value of variable, then you can use a short form of creating vars.

the := operator declares and assigns a value to a variable at the same time. Using this form you don’t have to provide the type of variable - the compiler will figure that out based on the value you passed.

Naming rules

Go has a set of naming rules that you’ll have to follow:

  • a name must begin with a letter
  • if the name begins with a Capital letter, it’s considered as exported and can be used outside of the current package. Otherwise, the variable/function/type can be used only inside the current package. THIS IS IMPORTANT!

These are all enforced rules. Simple!

One more additional rule set by the community is to use camelCase. It is also popular to abbreviate obvious variables - using i instead of index etc. That’s all you need to know about naming conventions.

Compiling Go code

Go code cannot be run directly. It has to be compiled to a binary format that your CPU understands. To do so, we need first to install Go:

  • Visit https://golang.org/dl/
  • Download package appropriate to your system
  • Follow the installation instructions page for your OS
  • Open a terminal/console
  • Execute go version. Version of Golang installed on your computer should be printed in the response.

Now, you’re are ready to create a Go program on your computer. Create a file named helloworld.go and copy-paste the content of our first Hello World program from online Go playground. Then, save the file. Now:

  • Run go build helloworld.go to compile the program. This will create an executable file.
  • Run the executable. On macOS/Linux just type ./helloworld, on Windows probably helloworld.exe

Learn Golang Basics


Conclusions

Nice! In this introductory post, you’ve compiled and executed a Go application on your computer. You’ve also learnt the basics of the language. You’re definitely ready to play with Golang to learn more! In the next posts, we’ll introduce more advanced concepts of the language. If you want to get a notification about the next post, subscribe to the newsletter. Thank you for reading!

Sources

Join our email list and get notified about new content

Be the first to receive our latest content with the ability to opt-out at anytime. We promise to not spam your inbox or share your email with any third parties.

More articles from talkoverflow

What are design patterns?

High-level overview OOP (object-oriented programming) gurus once concluded that it's pointless to reinvent the wheel every time you…

December 21st, 2019 · 1 min read

OpenID Connect + SPA + BACKEND API - Authentication in modern webapps

In this post, I’ll try to cover how the process of authentication will look like in Appwish platform . Appwish is made of frontend UI…

March 16th, 2020 · 5 min read
© 2019–2020 talkoverflow
Link to $https://facebook.com/talkoverflowsoftware/Link to $https://twitter.com/pjeziorowskiLink to $https://github.com/pjeziorowskiLink to $https://www.linkedin.com/in/patrykjeziorowski/