Golang - Installation and Hello World
Tags: go, 100daysofgo
Published: 2022-04-02 05:16:33

## Introduction

Moving on to the second day, we will be installing and setting up Go lang on our systems. The installation and setup are quite simple and not much demonstration is required, so further in the article, I will also make a hello-world program in GO. We will explore the basic program in GO and how to compile, run and build a GO program in this section. 

## Installing Go

Installing Go is pretty straightforward. You have to install the binaries from the official website as per your operating system. 

Head on to the [go.dev](https://go.dev/) which is the official website for the Go language. Click on the [Download](https://go.dev/doc/install) Tab and there should be all the required information. Install the installer as per your specific operating system. 

If you wish not to lead to any errors, keep the configuration for the installer as default and complete the installation process. 

## Setting up Environment variables

To make sure Go lang is perfectly installed in your system, type in CMD/Terminal/Powershell the following command:

```
go version
```

If you get a specific version of golang along with the platform and architecture of your system, you have successfully installed Go lang in your system. 

```
$ go version
go version go1.17.8 windows/amd64
```

If you get an output as a command not found or anything else, this is an indication that your Go installation was not successful. You need to configure your Environment variables properly or re-install the installation script. 

```
$ go version
bash: go: command not found
```


## Hello Gophers

Once the Go lang has been successfully installed in your system, we can start writing our first program. Yes, a `Hello World` program. It is not as simple as `print("hello world")` but a lot better than 10-15 lines of Java or C/C++. 

```go
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello,Gophers!")
}
```

So, this is so-called the `hello-world` program in Go, we will see each of the terms in detail next. But before that, let's get an idea of the style of the code. It is definitely similar if you are coming from C/C++ or Java, the package the main function. It will even feel like Python or Javascript when we explore other aspects. It has really a unique style of programming but feels familiar to programmers coming from any programming language, this might not be true for all programming languages though. 

### Packages 

A package in Go lang is a way to bundle up some useful functions or any other constructs. Using packages we can reuse components of a specific app in another. Packages in golang also help in optimizing the execution/compilation time by letting the compiler only compile the required packages. 

Here, we have the main package, which provides the entry point for the entire project. This is mandatory for creating executable programs as we need to have a start point. The file name can be anything, but for executing the code, you need to have a main package where your main function resides. It provides an entry point as a package, when we will run the file, we provide the file which actually acts as a package and the file that has a tag of main is the entry point for the program.

### Main Function

We have the main function where the main package is defined. It acts as a start point for a package. The main package will look for a main function inside the package. The main function doesn't take any parameter and nor does it return any value. When the function's scope ends, the program exits. 
 
The main function has significance only in the main package, if you define the main function in other packages excluding `main`, it works as a normal function. 

### Import Statements

We have an `import` keyword for importing packages from the standard library or other external packages from the internet. There are a lot of ways to import packages in golang like single, nested, multiple, aliased, dot import, and blank imports. We will see these different import styles in a dedicated section. Right now, we are directly importing a package, a single package. The pacakge is called the [fmt](https://pkg.go.dev/fmt) pacakge. It handles the format, input, and output format in the console. It is a standard package to perform some basic operations in golang.  

We can import it as a single direct import like:

```go
import "fmt"
```

OR 

Make multiple imports like:

```go
import (
    "fmt"
)
```

We can add multiple packages on each line, this way we do not have to write the keyword `import` again and again. It depends on what you want to do in the program. 

### Println function

We can access the functions from the imported packages, in our case we can use the functions from the `fmt` package. We have access to one of the functions like `Println`, which prints string on a new line. Syntactically, we access the function and call it by using the `dot` operator like:

```go
fmt.Println("Hi there!")
```

The [Println]() function takes in a parameter as a string and multiple optional parameters that can be strings or any variable. We will see how to declare variables and types in the next section. 

Here, the `P` in `Println` has significance as it allows us to distinguish private methods(functions in structs aka classes) from public methods. If a function begins with an uppercase letter, it is a public function. In technical terms, if the first letter of a method is upper case, it can be exported to other packages. 


## Running Scripts

Let's run the code and GO programming language to our resume. You can run a go source file assuming it has a main package with the main function using the following command:

```
go run <filename.go>
```

![GO run command](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833567/blog-media/o7i9spph2bfgemqonq8p.png)

This will simply display the string which we have passed to the `Println` function. If you didn't have a main package this command won't run and return you an error:

```
package command-line-arguments is not the main package
```

By executing the run command, we can are creating a executable in a system's temp folder,

For Windows, it's usually at:
```
C:\Users\acer\AppData\Local
```

You can get the location of the temp directory using CMD/PowerShell:

```
CMD:
echo %TEMP%

PowerShell:
$env:Temp
```

For Linux
```
/tmp
```

You can get the location of the temp folder using Terminal in Linux/macOS:

```
echo $TMPDIR
```

It doesn't create any executable in the current project or folder, it only runs the executable that it has built in the temp folder. The run command in simple terms **compiles and executes the main package**. As the file provided to the run command needs to have the main package with the main function, it will thus compile that source code in the provided file. 

To get the location of the executable file that was generated by the `run` command, you can get the path using the following command:

```
go run --work <filename>.go
```

![GO Run TMP file](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833643/blog-media/maqfd73xmiivrckc2acn.png)

This will print the path to the executable that it currently has compiled. 

For further readings on the `run` command in Go, you can refer to the [documentation](https://pkg.go.dev/cmd/go#hdr-Compile_and_run_Go_program).

## Creating Executables

We can go a step further by creating binary/executables with our source file using the `build` command:

```
go build <filename>.go
```

If you run this you would get an error as building a package requires a few things. The most important is the mod file.

```
go: cannot find main module, but found .git/config in D:\meet\Code\go\100-days-of-golang
    to create a module there, run:
    cd .. && go mod init
```

We need to create a mod file first before we build our script. 
A mod file in golang is the file that specifies the go version along with the packages and dependencies. It is like the `requirement.txt` but a bit different. 

We use the following command with the file that contains the main package among the other packages in the folder. We can even provide other packages to add to the mod file(see in detail in the future) 

```
go mod init <modname>
```

![GO Mod Init](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833683/blog-media/pdvkdpnanl3e0yzoenqb.png)

This will generate a `go.mod` file, this is a file that contains the list of dependencies and packages in the project. 
If you look at the mod file, it looks as follows:

```go
module sample-script

go 1.17
```

Currently, this is pretty simple and has very little detail, but as your project increases in complexity, this file populates with the modules and packages imported and used in the project. 

So, after creating the mod file, we can build the script which we tried earlier.

```
go build <filename>.go
```

![GO Build Command](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833745/blog-media/i0hnwsxxl0gglhh3rdoe.png)

So, this command generates an exe right in the current folder. This will generate the file named after the package which is mainly `filename.exe`. 

If you have a `go.mod` file in your project, just running the command will generate the exe file:

```
go build
```

![GO Build Command - Directory level](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833832/blog-media/sdw9zrlff3odtnhallyq.png)

NOTE: For the above command to work, you need to be in the directory which has the mod file for your project. It basically bundles the listed packages and creates the executable named after the package which is named `main`. Thus it generates a different file name as `filename.go.exe`

We can also provide an output file as the exe file name, this can be done with the following command:

```
go build -o <executable_file> <source_filename>.go
```

![GO Build Output file](https://res.cloudinary.com/techstructive-blog/image/upload/v1648833932/blog-media/t5dfhx0va7reyjjygfnq.png)

For further reading on the `go build` command, head over to this [documentation](https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies) page.

Link to all of the code and resources is mentioned in this [GitHub](https://github.com/Mr-Destructive/100-days-of-golang) repository.


## Conclusion

So, from this second post, we were able to set up the Go language in our system and write our first `hello-world` program. This was a bit more than the setup and installation guide as it is quite boring to demonstrate the installation procedure being quite straightforward. Hopefully, you followed so far and you were able to pick up things in the go landscape. Thank you for reading and if you have any questions, suggestions, or feedback, let me know in the comments or the provided social handles. See you tomorrow, until then Happy Coding :)