Thursday, February 2, 2017

Go - Quick Guide

Go - Overview

Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries.
Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries.
The Go programming language was announced in November 2009 and is used in some of the Google's production systems

Design Principles

  • Support for environment adopting patterns similar to dynamic languages. For example type inference (x := 0 is valid declaration of a variable x of type int)
  • Compilation time is fast.
  • InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement.
  • Conciseness, Simplicity, and Safety
  • Support for Interfaces and Type embedding.
  • Production of statically linked native binaries without external dependencies.

Features excluded intentionally

To keep language simple and concise, following features commonly available in similar languages are ommitted.
  • No support for type inheritance
  • No support for method or operator overloading
  • No support for circular dependencies among packages
  • No support for pointer arithmetic
  • No support for assertions
  • No support for generic programming

Go Programs

A Go program can vary from 3 lines to millions of lines and it should 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.
This tutorial assumes that you know how to edit a text file and how to write source code inside a program file.

Go - Environment Setup

Try it Option Online

You really do not need to set up your own environment to start learning Go programming language. Reason is very simple, we already have set up Go Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.
Try following example using Try it option available at the top right corner of the below sample code box:
package main

import "fmt"

func main() {
   fmt.Println("Hello, World!")
}
For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.

Local Environment Setup

If you are still willing to set up your environment for Go programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The Go Compiler.

Text Editor

This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.
The files you create with your editor are called source files and contain program source code. The source files for Go programs are typically named with the extension ".go".
Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.

The Go Compiler

The source code written in source file is the human readable source for your program. It needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per instructions given.
This Go programming language compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler.
Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.
Following section guides you on how to install Go binary distribution on various OS.

Download Go archive

Download latest version of Go installable archive file from Go Downloads. At the time of writing this tutorial, I downloaded go1.4.windows-amd64.msi and copied it into C:\>go folder.
OSArchive name
Windowsgo1.4.windows-amd64.msi
Linuxgo1.4.linux-amd64.tar.gz
Macgo1.4.darwin-amd64-osx10.8.pkg
FreeBSDgo1.4.freebsd-amd64.tar.gz

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

Extract the download 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.
OSOutput
Linuxexport PATH=$PATH:/usr/local/go/bin
Macexport PATH=$PATH:/usr/local/go/bin
FreeBSDexport 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 window's PATH environment variable. Restart any open command prompts for the change to take effect.

Verify installation

Create a go file named test.go in C:\>Go_WorkSpace.
File: test.go
package main

import "fmt"

func main() {
   fmt.Println("Hello, World!")
}
Now run the test.go to see the result:
C:\Go_WorkSpace>go run test.go
Verify the Output
Hello, World!

Go - Program Structure

Before we study basic building blocks of the Go programming language, let us look a bare minimum Go program structure so that we can take it as a reference in upcoming chapters.

Go Hello World Example

A Go program basically consists of the following parts:
  • Package Declaration
  • Import Packages
  • Functions
  • Variables
  • Statements & Expressions
  • Comments
Let us look at a simple code that would print the words "Hello World":
package main

import "fmt"

func main() {
   /* This is my first sample program. */
   fmt.Println("Hello, World!")
}
Let us look various parts of the above program:
  1. The first line of the program package main defines the package name in which this program should lie. It is a must statement as Go programs runs in packages. main package is the starting point to run the program. Each package has a path and name associated with it.
  2. The next lineimport "fmt" is a preprocessor command which tell the Go compiler to include files lying in package fmt.
  3. The next line func main() is the main function where program execution begins.
  4. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. Comments are also represented using // similar to Java or C++ comments.
  5. The next line fmt.Println(...) is another function available in Go which causes the message "Hello, World!" to be displayed on the screen. Here fmt package has exported Println method which is used to display message on the screen.
  6. Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means that a function or variable/constant is accessible to importer of the respective package.

Execute Go Program:

Lets look at how to save the source code in a file, and how to compile and run it. Following are the simple steps:
  1. Open a text editor and add the above-mentioned code.
  2. Save the file as hello.go
  3. Open a command prompt and go to the directory where you saved the file.
  4. Type go run hello.go and press enter to run your code.
  5. If there are no errors in your code then you will be able to see "Hello World" printed on the screen.
$ go run hello.go
Hello, World!
Make sure that go compiler is in your path and that you are running it in the directory containing source file hello.go.

Go - Basic Syntax

You have seen a basic structure of Go program, so it will be easy to understand other basic building blocks of the Go programming language.

Tokens in Go

A Go program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens:
fmt.Println("Hello, World!")
The individual tokens are:
fmt
.
Println
(
"Hello, World!"
)

Line Seperator

In Go program, the line seperator key is a statement terminator. That is, each individual statement don't need a special seperator like ; in C. Go compiler internally places ; as statement terminator to indicate the end of one logical entity.
For example, following are two different statements:
fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")

Comments

Comments are like helping text in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below:
/* my first program in Go */
You cannot have comments within comments and they do not occur within a string or character literals.

Identifiers

A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
identifier = letter { letter | unicode_digit } .
Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers:
mahesh   kumar   abc   move_name   a_123
myname50   _temp   j   a23b9   retVal

Keywords

The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.
breakdefaultfuncinterfaceselect
casedefergomapstruct
chanelsegotopackageswitch
constfallthroughifrangetype
continueforimportreturnvar

Whitespace in Go

A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.
Whitespace is the term used in Go to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:
var age int;
There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement:
fruit = apples + oranges;   // get the total fruit
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

Go - Data Types

In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
The types in Go can be classified as follows:
S.N.Types and Description
1Boolean Types
They are boolean types and consists of the two predefined constants: (a) true (b) false
2Numeric Types
They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program.
3string types:
A string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string.
4Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Function types h) Interface types i) Map types j) Channel Types
The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will see basic types in the following section, whereas, other types will be covered in the upcoming chapters.

Integer Types

The predefine architecture-independent integer types are:
S.N.Types and Description
1uint8
Unsigned 8-bit integers (0 to 255)
2uint16
Unsigned 16-bit integers (0 to 65535)
3uint32
Unsigned 32-bit integers (0 to 4294967295)
4uint64
Unsigned 64-bit integers (0 to 18446744073709551615)
5int8
Signed 8-bit integers (-128 to 127)
6int16
Signed 16-bit integers (-32768 to 32767)
7int32
Signed 32-bit integers (-2147483648 to 2147483647)
8int64
Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

No comments:

Post a Comment