DEV Community

Cover image for Golang - Installation and Hello World
Meet Rajesh Gor
Meet Rajesh Gor

Posted on • Edited on • Originally published at mr-destructive.github.io

Golang - Installation and Hello World

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 which is the official website for the Go language. Click on the Download 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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++.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello,Gophers!")
}
Enter fullscreen mode Exit fullscreen mode

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 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:

import "fmt"
Enter fullscreen mode Exit fullscreen mode

OR

Make multiple imports like:

import (
    "fmt"
)
Enter fullscreen mode Exit fullscreen mode

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:

fmt.Println("Hi there!")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

GO run command

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

CMD:
echo %TEMP%

PowerShell:
$env:Temp
Enter fullscreen mode Exit fullscreen mode

For Linux

/tmp
Enter fullscreen mode Exit fullscreen mode

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

echo $TMPDIR
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

GO Run TMP file

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.

Creating Executables

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

go build <filename>.go
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

GO Mod Init

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:

module sample-script

go 1.17
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

GO Build Command

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
Enter fullscreen mode Exit fullscreen mode

GO Build Command - Directory level

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
Enter fullscreen mode Exit fullscreen mode

GO Build Output file

For further reading on the go build command, head over to this documentation page.

Link to all of the code and resources is mentioned in this GitHub 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 :)

Top comments (5)

Collapse
 
mpatelpa profile image
mpatelpa

I m newbie in go and using go 1.21.0. Following the instruction under "Creating executes" the command go mod init .go and running the build command (go build), overwrites source code with the compiled binary file. Changing go mod init .go to go mod init (dropped the file extension) and running the build command works as expected.

Collapse
 
mpatelpa profile image
mpatelpa

Repost (fixed formatting issues)

I m newbie in go and using go 1.21.0. Following the instruction under "Creating executes" the command go mod init <filename>.go and running the build command (go build), overwrites source code with the compiled binary file. Changing go mod init <filename>.go to go mod init <filename> (dropped the file extension) and running the build command works as expected.

Collapse
 
mr_destructive profile image
Meet Rajesh Gor

Sorry, the mod name can be anything, it is usually a project name or a git repo URL like git mod init github.com/username/reponame. Thank you for pointing that out, it might be a bit confusing with that example.

Collapse
 
snowlyg profile image
snowlyg

--work !! Haha, I see this param first time.

Collapse
 
mr_destructive profile image
Meet Rajesh Gor

Funny isn't it? It has a different vibe to it. Just make it work.