Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited on • Originally published atmr-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 thego.dev which is the official website for the Go language. Click on theDownload 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 modeExit 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 versiongo version go1.17.8 windows/amd64
Enter fullscreen modeExit 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 versionbash: go: command not found
Enter fullscreen modeExit fullscreen mode

Hello Gophers

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

packagemainimport("fmt")funcmain(){fmt.Println("Hello,Gophers!")}
Enter fullscreen modeExit fullscreen mode

So, this is so-called thehello-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 excludingmain, it works as a normal function.

Import Statements

We have animport 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 thefmt 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 modeExit fullscreen mode

OR

Make multiple imports like:

import("fmt")
Enter fullscreen modeExit fullscreen mode

We can add multiple packages on each line, this way we do not have to write the keywordimport 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 thefmt package. We have access to one of the functions likePrintln, which prints string on a new line. Syntactically, we access the function and call it by using thedot operator like:

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

ThePrintln 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, theP inPrintln 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 modeExit fullscreen mode

GO run command

This will simply display the string which we have passed to thePrintln 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 modeExit 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 modeExit fullscreen mode

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

CMD:echo %TEMP%PowerShell:$env:Temp
Enter fullscreen modeExit fullscreen mode

For Linux

/tmp
Enter fullscreen modeExit fullscreen mode

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

echo $TMPDIR
Enter fullscreen modeExit 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 termscompiles 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 therun command, you can get the path using the following command:

go run --work <filename>.go
Enter fullscreen modeExit fullscreen mode

GO Run TMP file

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

For further readings on therun command in Go, you can refer to thedocumentation.

Creating Executables

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

go build <filename>.go
Enter fullscreen modeExit 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 modeExit 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 therequirement.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 modeExit fullscreen mode

GO Mod Init

This will generate ago.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:

modulesample-scriptgo1.17
Enter fullscreen modeExit 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 modeExit 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 mainlyfilename.exe.

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

go build
Enter fullscreen modeExit 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 namedmain. Thus it generates a different file name asfilename.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 modeExit fullscreen mode

GO Build Output file

For further reading on thego build command, head over to thisdocumentation page.

Link to all of the code and resources is mentioned in thisGitHub repository.

Conclusion

So, from this second post, we were able to set up the Go language in our system and write our firsthello-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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mpatelpa profile image
mpatelpa
  • Joined

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

CollapseExpand
 
mpatelpa profile image
mpatelpa
  • Joined

Repost (fixed formatting issues)

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

CollapseExpand
 
mr_destructive profile image
Meet Rajesh Gor
Meet a.k.a. Mr_Destructive | Django Developer | Vim & Linux Enthusiast
  • Location
    Mumbai, India
  • Joined

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

CollapseExpand
 
snowlyg profile image
snowlyg
  • Location
    DongGuan,China
  • Education
    ChangeSha
  • Work
    Chindeo
  • Joined

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

CollapseExpand
 
mr_destructive profile image
Meet Rajesh Gor
Meet a.k.a. Mr_Destructive | Django Developer | Vim & Linux Enthusiast
  • Location
    Mumbai, India
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Meet a.k.a. Mr_Destructive | Django Developer | Vim & Linux Enthusiast
  • Location
    Mumbai, India
  • Joined

More fromMeet Rajesh Gor

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp