The Simple Golang Tutorial: Modules and Basic Syntax
Tags: go
Published: 2021-04-05 08:14:07

If you've been following my other articles for the last few weeks, you will notice I was mostly writing about DevOps. This week is going to be something different. I will cover the basics of one of the most trending programming languages in IT right now - golang.

Golang is starting to take the place of Python in many command-line and web applications. Each one has its own merits, which I won't discuss here. What I will do, though, is give you the ropes so that you can code something basic in Golang. In part, I called this tutorial "Simple" because I only cover the essential and bare minimum aspects that you need to write code. Many programmers struggle to use one language after working for a long time with another.

This tutorial will not show you how to install Golang. This task is quite simple to do. On Linux, look for a package called "go" or "golang" in your package manager. For other operating systems, or if you want to use the latest version, follow the instructions at the [Golang documentation page](https://golang.org/doc/install).

So without further ado, let's begin.

## (not) Hello World

We start by seeing precisely *how* to run Golang code. I'm not a big fan of Hello World programs at this point of the learning process because you have to copy and paste them into your editor, and you’re not learning anything except perhaps how to write a print statement, so we’re going to skip that stuff here.

Golang source files have a .go file extension.

To run a golang program, you navigate to the folder that contains your .go file and run:

```
go run .
```

The thing about this command is that you're probably wondering by now, *” what does this ‘.’ do?”* In some operating systems, the dot represents the current directory. The Golang language documentation for the `run` command says that this command compiles and runs a binary. To avoid having you going down an unnecessary rabbit hole, I won't link to that page.

From the documentation I’ve gathered [here](https://golang.org/pkg/cmd/go/), we are indeed passing a directory to `go run`: It takes all of the .go source files in that folder and compiles them together into a binary which it then runs. Exactly where this binary is placed is a question for later. For now, the critical part is what happens when you have unrelated .go files in the same folder as the ones you're compiling.

Well, those get compiled too.

---

So that means to avoid including unwanted functionality - or even getting compilation errors from your untested .go files - you must keep your source files for each program in separate folders. Most other languages don't care what else you have in your folders; golang is different in this regard.

You see, all golang code exists in __modules__; They are similar to Java packages in that they bundle a bunch of functions and global variables together. It's possible to run a module, as we will see later, but for now, it suffices to say that the argument after `run` doesn't always have to be a dot, and you don't always have to be in the same directory as the source files. You can pass any folder path to `go run`, and it’ll run the files in that folder.

## Modules

Ok, so how do you create a module? The answer is with the `go mod init` command. The argument after `init` is the name of the module that you are about to create. You can call it anything, but there are restrictions to its naming if you ever publish your module (a topic beyond the scope of this guide for the sake of simplicity).

The rule is *one folder, one module*. You can only create one module in a folder. Subsequent attempts to create more modules in the same folder will result in an error:

```
$ go mod init foobar.com/example
go: creating new go.mod: module foobar.com/example
$ go mod init examplejedi
go mod init: go.mod already exists

```

As you can see, this creates a single file `go.mod` in the current folder, which has the name of the module and the golang version used to make it:

```
$ cat go.mod
module foobar.com/example

go 1.15
```

Alright, so now we've seen how to run a golang script and create a module, but what about writing the code itself? First, we make a file with the .go file extension and put the following line at the top of the file:


```
package example
```

`example` here gets replaced by the name of the module you just made. If it has a slash in the middle and two parts to the name, then use the last part of the name.

What we just did is that we declared that this file belongs to the `example` module (the foobar.com/example module in particular). Now you no longer have to worry about unrelated files being compiled together; just give them different packages names.

## Importing other modules

What happens next depends on what you want to write, but generally, you will be using other people's modules. To do that, you import the respective module like this:

```
import "fmt"
```

This will import the `fmt` module, which is used to format text.

## Functions and statements

Now let's see how you define functions.


```
// Hello returns a greeting for the named person.
func Hello(name string) string {
    // ...
}
```

What I have just demonstrated is threefold. The function signature begins with “func”, followed by the name of the function. Then each argument is specified with the name first, and then its type after it. Even the return value is set after the parentheses instead of at the beginning of the line.

I have also shown how to write comments. They use `//`, just like in C (the C99 variant), C++, Java, and some other languages.

Golang also supports multiline comments that look like this:

```
/*
 * This is a multi-line comment
 */
```

They begin with `/*` and end with `*/`.

This is how we print a line with the `fmt` module:

```
fmt.Println("Go!")
```

As you just saw, modules expose functions that you can call. In this case, the `fmt` module contains a `Println` function that takes a string argument and prints it on standard output.

To return from a function, we use the ubiquitous  `return` statement:

```
return “Hello!”
```

When used inside a function, it will return whatever value comes after it on the right to the calling function.

A sneak peek at how variables are declared (I will post a more detailed version next week):

```
// notice how there's no type specified
message := fmt.Sprintf("Hi, %v. Welcome!", name)
```

This statement **creates** a variable called `message`. It initializes its value to the output of `fmt.Sprintf`, a function that substitutes placeholders with the values of the second, third, and subsequent arguments.

Note the mention of the word “creates.” This is very important. Variables can only be created once, and as you may already know, it is an error to try to make a variable twice. If you want to reassign to a variable, use `=` instead of `:=`.

---

That's all for today. Next week we will be looking at, among other things, variables & types and some operators. We saw how while Golang can be similar to C and Java at times, it also exhibits some unique behavior as we saw for compiling golang modules.