LanguagesIntroduction to Go

Introduction to Go

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The language Go simplified programming in a number of ways. The trouble one has to go through while developing an application in a language like C/C++ is immense. For example, one has to take memory management tasks very seriously. It’s up to the programmer to decide whether to allocate space in the heap or stack and deallocate it perfunctorily to avoid leaks.

Go has a garbage collector to clean up the memory on behalf of the programmer. This is one of the many ways Go makes writing code easier without compromising the ability to make code that runs pretty fast. The concepts behind Go are influenced by many languages but the syntax mainly adheres to C/C++ with a few trimmings here and there. The learning curve is almost flat, at least for the programmers who have a little background in them. This article gives an introductory idea of Go as a language, its history, abstract model and some basic concepts to begin with.

Brief history

The Go language, often called Golang, owes its origin to Robert Griesemer, Rob Pike and Ken Thompson in September 2007. Started as a part-time endeavor, it quickly garnered interest among other Google engineers and became a full-time project in mid 2008. Soon Ian Taylor and Russ Cox joined in and contributed to push the project from prototype to production.

They say the primary motivation for creating a new language is the frustration over the complexity involved in developing software with existing tools such as C, C++, Java, etc. Engineers like Ken Thompson thought of starting up fresh with a language that is designed to deal with the scenario right from the buildup. This gave birth to the language Go. People call it golang only because the name of the website is golang.org. The language Go is built with the goal of achieving the right balance between efficient compilation, execution and ease of programming. The syntax is heavily influenced by C, with valuable inputs from other language families such as Pascal, Modula, Oberon, Newsqueak, Limbo, and more.

Getting started

The key to learning any new language is to understand the abstract principles behind it, its syntax and how to use the standard libraries and express the syntaxes in the form of a program statement. So for the programmer who wants to jump in and learn a new language, the only stumbling block is these issues – which this series will guide you through. The logic you employ to do the task remains constant.

Go abstract model

Down the years C has been a de facto, low-level language for developing complex applications that closely reflects the architecture of the target machine. Although there is no such thing as a universal low-level language that can be used to accurately map the architecture, the abstract model of C language closed the gap quite effectively. But C has been reigning since computers had single CPUs with low memory. Memory is expensive so we must take utmost care to free it up meticulously as things go out of scope. In this day and age of multicore CPUs with memories that are counted in Gigabytes, efficient programming with C has been considerably reduced, if not made irrelevant. This is particularly true from the point of view of a programmer. The engineers at Google felt the need to develop a new language that is able to squeeze out the benefit of modern hardware and relieve the programmer of some of the strenuous tasks involved with low-level programming. However, Go is equally equipped with a number of high-level features and can be easily used to deal with web services or a desktop application. In short, Go can be viewed as a New Age C with a modern programming paradigm.

A language that can be used to write scalable code is as important as raw speed if not more so. Perhaps this is the reason C, as a serial language, has various libraries like POSIX thread and OpenMP to enable it to derive the benefit of writing multithreaded code. But the problem is that those features incorporate extensive complexity, making it not only hard to code but also difficult to scale. Go is designed to use concurrency right from the buildup, where things can run in parallel using multicore facility and distribute tasks across multiple threads.

Go includes a rich set of libraries that can be included as needed to write complex web applications with ease.

Go syntaxes

Go syntaxes include:

Unambiguity

Go developers were keen on making the language syntax as consistent and unambiguous as possible. The idea is that the compiler must give an accurate signal when an error occurs and display a message that is to the point and helpful. This is something very frustrating in the case of the C/C++ compiler. For example, the syntax for writing a function and a global variable is the same. As a result, the compiler cannot easily sort the ambiguity and give a clear sign of the error. Go does not allow variables to be declared, and the compiler quickly flags an error in that case.

Statement terminator

Unlike C/C++ the need to end every statement with a semicolon is removed. Here, Go adopts the JavaScript principle of implicit semicolon insertion by the parser. This simply means that Go is completely free from explicit semicolon insertion as a statement terminator.

Braces constraint

Go added a specific constraint for using braces. A brace must be opened at the end of the line of a flow-control statement. Unlike C/C++ where braces can be anywhere after the flow control statement, Go maintains this specific constraint.

One type of loop

Go allows only one type of loop, that the for-loop. There is no while or do…while loop. However, there are different ways of writing that may sometimes resemble a while-loop.

Pointers

Go has pointers but you cannot do pointer arithmetic. Pointer arithmetic can be easily mishandled and do some nasty things, be it intentionally or due to error. Go took care of that and made sure this does not happen, keeping the power of pointer very much in the programming.

Note that this is not a complete syntax reference but a few points that are going to capture our attention given a first look at source code.

A glimpse of the Go code structure

There are three parts to Go source code.

  1. Package statement declaration. This is akin to the namespace of C++ or Java packages. Since Go libraries are arranged in packages, we must import them as per our requirements much like the include statement of C/C++ or Java import. In Go, a package named main is important and every program must contain a main package, which encompasses the main function, the entry point of the program.

  2. The import statement is used to import the specific libraries that the current Go source file likes to use. For example, there is a standard package named fmt. This package implements formatted I/O with functions analogous to C’s printf and scanf. Unlike C/C++ or Java the import statement in Go does not include the source code of the imported element in the current compilation unit; rather the packages are imported during the linking phase.

  3. The final part contains the program definition with type declaration, variables and functions and your logic.

Listing 1: file hello.go

package main
import "fmt"
func main(){
fmt.Println("Hello! from Go");
}

This is a simple yet complete Go program to print a hello statement. Note that Println is a function declared in the fmt package and we use the dot operator to access it. This function writes to standard output with spaces added between operands and a new line is appended. It returns the number of bytes written and any write error encountered in the process.

The simplest way to access Go documentation is to use the command. For example, if we want to see the documentation related to the package fmt or function Println, we may do so as follows:

$ go doc fmt

or

$ go doc fmt.Println

To run the code

$ go run ./hello.go

It’s a shortcut for compiling and running in a single step. This is useful in viewing the output in quick development. It uses a temporary directory to build the code and cleans it up after execution. We can view the location of the temporary file with the command go run –work ./hello.go. Another way is to build and then execute the code as follows:

$ go build ./hello.go
$ ./hello.go

Conclusion

Languages such as C/C++ are reliable and fast but they also make it hard to incorporate modern programming features such as multithreading or parallel processing. Manual memory may have its own merit, but building complex and large systems can be quite a pain.

Bjarne Stroustroup once stated that “a garbage collector which could be optionally enabled would be part of C++0x, but there were enough technical problems that I have to make do with just a detailed specification of how such a collector integrates with the rest of the language, if provided.”

Unlike Go we can add features in C/C++ but they are not built with them. The languages that run in VM are slow by comparison and are not fit for low-end system development or software that requires fast processing. Go is built with and open to many possibilities. That is perhaps the reason why its popularity has grown manifold in recent years.

 
 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories