Ontoborn.com

@Ontoborn99

Basics of Golang [For Beginners]

What is Golang?

Golang is a programming language initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go programming language is a statically-typed language with syntax similar to that of C. It provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps. It also provides a rich standard library.

Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multi core and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It’s a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.

Go Programs

A Go program can vary from 3 lines to millions of lines and it should also be written into one or more text files with extension “.go”; for example, hello.go. You can use “vi”, “vim” or any other text editor to write your Go program into a file.

Setting up Go Environment

Environment setup can be done in few steps

Download and install the latest 64-bit Go.Go installable archive file from (which also sets most of the environmental variables for you).

Click here to download

Installation on UNIX/Linux/Mac OS X, and FreeBSD

Extract the downloaded archive into /usr/local, creating a Go tree in /usr/local/go. For example:

tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz

Add /usr/local/go/bin to the PATH environment variable.

OSOutputLinuxexport PATH=$PATH:/usr/local/go/binMacexport PATH=$PATH:/usr/local/go/binFreeBSDexport PATH=$PATH:/usr/local/go/bin

Installation on Windows

Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin directory in windows PATH environment variable. Restart any open command prompts for the change to take effect.

Verify Installation

Now run the test.go to see the result:

Getting Started with Golang

Packages

Every Go program is made up of packages.

Programs start running in package main.

This program is using the packages with import paths “fmt”

Here is an example

Imports

We can write imports as

Or

Functions

The general form of a function definition in Go programming language is as follows:

A function can take zero or more arguments.

In example below , add takes two parameters of type int.

Notice that the type comes after the variable name.

Now run the function.go to see result

Variables

A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and also contains a list of one or more variables of that type as follows:

The var statement declares a list of variables; as in function argument lists, the type is last.

A var statement can be at package or function level. We see both in the example below.

Now run the variables.go to see result

For Loop

A for loop is a repetition control structure that will allow you to efficiently write a loop that needs to execute a specific number of times.

The syntax of a for loop in Go programming language is:

Go has only one looping construct, the for loop.

The basic for loop has three components separated by semicolons:

  • the init statement: executed before the first iteration
  • the condition expression: evaluated before every iteration
  • the post statement: executed at the end of every iteration

The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.

The loop will stop iterating once the boolean condition evaluates to false.

Note: Unlike other languages like C, Java, or Javascript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

Now run the for.go to see result

Arrays

Go programming language also provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows:

For example, to declare a 10-element array called balance of type float32, use this statement:

You can initialize array in Go either one by one or using a single statement as follows:

The type [n]T is an array of n values of type T.

The expression

var a [10]int

declares a variable a as an array of ten integers.

An array’s length is part of its type, so arrays cannot be resized. This seems limiting, but don’t worry; Go provides a convenient way of working with arrays.

Let us see an example

Now run the arr.go to see result

Slices

Golang Slice is an abstraction over Go Array. As Go Array allows you to define type of variables that can hold several data items of the same kind but it do not provide any inbuilt method to increase size of it dynamically or get a sub array of its own. Slices covers this limitation. It provides many utility functions required on Array and is widely used in Go programming.

Defining a slice

To define a slice, you can declare it as an array without specifying size or use make function to create the one.

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

The type []T is a slice with elements of type T.

This expression creates a slice of the first five elements of the array a:

a[0:5]

Let us understand it by an example

Now run the slice.go to see result

Structure

structure in golang is a user defined data type available in Go programming, which also allows you to combine data items of different kinds.

Defining a Structure

To define a structure, you must use type and struct statements. The struct statement defines a new data type, with more than one member for your program. type statement binds a name with the type which is struct in our case. The format of the struct statement is this:

Once a structure type is defined, it can be used to declare variables of that type using following syntax.

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:

Now run the struct.go to see result

References

Tutorials Point

Hire Golang Developers

You can hire Golang developers at an hourly, weekly or monthly basis at http://ontoborn.com

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

More by Ontoborn.com

Topics of interest

More Related Stories