Skip to main content

How to start with Go Language - A Google's Programming Language

It's been always fun to start programming with a brand new language. And, as a Programmer, it's absolutely worth to keep you updated with the new languages as you come across.

Every programming language in this world is been designed to solve a problem in mind. So learning a new language would help you to solve your problem efficiently if the language offers flexibility to do so.

I am going to share the knowledge on the new language; atleast for me 😉 (released on 10 November 2009) which i have explored on. The name of new language is Go. Yes it is Google's language; Golang.

Gopher
Source: sdtimes.com
Will see what Google says about the new Language,
Go is a statically typed, compiled language in the tradition of C, with memory safety, garbage collection, structural typing, and CSP-style concurrency.
Yes, Go language is mainly designed to deal with morden days problems in the computing world. The Golang has the built-in feature of concurrency i.e deal with multiple tasks at same time which would leverage the multicore platforms and networking to design distributed systems.

There are plenty of talks and articles about Go language features. The Awesome Go github page is where you can find the complete curated list of resource and the talk Concurrency is not Parallelism given by Rob Pike explains everything about the concurrency.

Setting up the Go Environment

To start with the Hello World program, let us set up the work environment for Go. To start with Golang, you should have the go binaries in place to compile and run the app. Download and install the Go binary from golang site. The latest stable build is 1.10.3.

I would suggest to use VS Code as IDE for Golang as it  provides to use go toolchains to improve development experience. You can download and install the VS Code from the visual studio site based on you machine arch. Once you are done installing the vs code editor, you have to install the extension i.e go toolchains for golang. Just click on the Extensions tab and type Go in the IDE. The first item listed in the panel is what you should install. This extension is developed and maintained by Microsoft.

Go Extension for VS Code
Go extension

After installing the extension, Open the command panel by pressing Ctrl+Shift+P and type Go: and select the option Go: Install/Update Tools to install the required tools to work with Go files. Once all the required tools are installed, you are ready to Go 🙌.

Setting GOPATH for your project

It is mandatory to set the environment variables for Go to work smooth. When we build .go file, go compiler would search the given .go file under GOPATH and GOROOT. The GOROOT is the folder where the installation has been done. Usually the GOPATH environment would point to the go folder of user directory i.e in Windows PC, it is C:\Users\<username>\go.

But if we create our new project in different folder other than GOROOT or GOPATH then we should set the env variable GOPATH to point our new location. Otherwise Go build would fail if your project's source is not under either of Go folders. So we have to set the GOPATH to the folder where our source files are.

To set the GOPATH to our source folder, we have to open a command prompt from the folder where our source is and set GOPATH environment variable.

If it is Powershell,

    >$env:GOPATH="path/to/your/source/folder"

If it is Bash shell,

    >export GOPATH="path/to/your/source/folder"

If it is Cmd shell,

    >setx GOPATH="path/to/your/source/folder"

And upon successful build, the binary file for the main package would be generated in the current working directory. If you want to keep you binary in the bin folder, you should have set the GOBIN environment variable to you bin directory. By default the GOBIN would be empty.

If you want to see all the environment variables for go, you could execute the below command to see the list

    >go env

Once our GO environment is ready, we start writing code.

Hello World - Your First Program

Before start writing our first Golang program, let's see how go project files are organized. The basic project folder structure is as shown below,

    C:/Golang
       ├───pkg
       ├───bin
       └───src
           └───package1

Here the pkg folder is where all the object files of source packages would be stored. The bin folder would have the commands of the project. The src folder is where all the source packages would be located.

Lets print Hello World in the console. Create main.go file under src folder and write code as shown below.

    package main
    
    import "fmt"

    func main() {
       fmt.Println("Hello World!")
    }

That's all, our first ever Go program is ready to build and run.

Build and Run your Go Program

To build our program, you just need to click Debug tab in VS Code and click on Launch play button as shown below

Build and Run in VS Code

Sometimes you might get issues 😠 while building the program via VS Code. VS Code would a open popup to resolve the issue in launch.json file. The issue is because of the incorrect GOPATH.

Build error
To resolve this issue, you have to update the program to point the source directory. Just use the below settings for your launch.json file
     {
      // Use IntelliSense to learn about possible attributes.
      // Hover to view descriptions of existing attributes.
      // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
     "version": "0.2.0",
     "configurations": [
        {
          "name": "Launch",
          "type": "go",
          "request": "launch",
          "mode": "debug",
          "program": "${workspaceRoot}/src"
          "env": {},
          "args": []
        }
      ]  
    }
If you want to set GOPATH for this program, we set that using the env attribute. And if we need to pass some arguments to the application then we can use the args attribute.

Running Go apps from Command Line

Though we could able to build and run our hello world application from VS Code Debug tab, we can also build and run the go apps from command line. Go provides build, run and install commands to build and run the apps.

The build command

The build command is used to build the go packages and command. Before building the go package, we have to set the GOPATH for the source directory. The basic example for build command is given below,

     >go build -i src/main.go
     >Hello World!

Here the option -i would install all the dependencies of the main.go. For more options, we can execute the help command like go help <command name>.

The run command

The run command could be used to compile and run the go source file. We can provide the build options when we use the run commands.

For example,

     >go run -i src/main.go

The i option with run command would install the dependencies as we used in the build command.

Conclusion

In this post, I have shared that how to start with the Go language using VS Code editor as and IDE and will continue to share the posts about go language which will you some idea about the usage.

Thanks for reading 🙏. Comments are always welcome 👍

Comments

Popular posts from this blog

Control Statements in Golang

The beauty of every programming language is defined by the flow of the program i.e by the Control Statements!. Yes, Control statements defines the flow of the program through the blocks of  statements defined. Go language provides control statements as like other languages but with different usage possibilities.

Types Of Control Statements There are three types of control statements available with Golang: Conditional, Unconditional and Loop.
Conditional Statements Conditional statements are statements which would execute the branch of statements conditionally. They are if, if-else , else-if and switch.
If statementif control statement controls the execution of the branch of statements based on the condition given. The syntax is,
if conditions { // statements to be executed } Let's look at the below example
if age == 5 { fmt.Println("Come back when you turn 6 to join 1st standard!") } In Golang, we can have initialization statement right before the conditional …

Variable declarations in Go language

Every programming language in this world provides options to declare and define variables and used by parts of the program. So Go does the same.

The wiki states that a variable is
a symbolic name associated with a value and whose associated value may be changedBut in more technical way, a variable is a memory location with name which might hold values and may change later.


Go provides different options to declare and define the variables. Let's see how we can declare variable in Golang.
Variable declarationA variable in go could be declared as follows,
package main import "fmt" var a = "has some value" func main() { fmt.Println(a) } Here the variable a is declared and initialized with the value "has some value". The type of the variable is inferred from the value been assigned.
Supported Types in GolangGo supports the following primitive types

BaseTypesDescriptionNumerics uint, int (8,16,32,64 bits), float (32, 64 bits),
 complex with 64, 128 bits, byt…