Menu Close


Introduction to Go

Go also known as GoLang is a third generation computer language. It was designed by a team of three at Google. The initial intention was to create a system language to replace C++ but this was changed later after Go has implemented a garbage collector. Now Go is just another high-level language for cloud services and parallel computing.

Language Syntax

Go syntax is derived from C++ family with influences from Python language. It is a curly braced language with type inference. That means we can create variables without declaring them explicit. Most keywords are English words or abbreviations. The symbols, operators and punctuation are similar to C++.

Example: “hello world” program.


  • A statement is on a single line of code or several lines of code;
  • It is a curly brackets language because the blocks of code are separated by  { };
  • Semicolons are not required  at the end of a line;
  • Strings are separated by double quotes “” or “;
  • Function is declared using “func” keyword;
  • Strings are Unicode and the source code is also Unicode;
  • Single line comment starts with two backslash symbols // like in C.
  • Multiple line comments start with /* and end with */ like in C.

Comparing this with Level language:

  • indentation is not mandatory;
  • fmt and func are madeup keywords not English;
  • the main program in go is called main alwais but in Level has proper name;
  • in level the end of statement is alwais finalized with “;”


The var statement declares a list of variables. In variable declaration the type name is specified last. This is better than Java where the type is specified first. A var statement can be at package or function level. So we can have a global variable and a local variable.

We see both in this example.

Initial value

A var declaration can include one initializer for each variable. If an initializer is present, the type can be omitted. The variable will take the type of the initializer. This is called type inference.

Type inference

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

Note: Outside of a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.


In Go it is good to use constants instead of normal variables to define numbers or other values that will not change during program execution.

  • Constants are declared like variables, but with the const keyword.
  • Constants can be character, string, boolean, or numeric values.
  • Constants cannot be declared using the := syntax.

Numeric Constants

Numeric constants are high-precision values. An untyped constant takes the type needed by its context.

Basic Types

In Go languages all variables have a type that can’t be changed once established. Go is has predefined types and user defined types.

The basic types are the most simple predefined types:

  • bool;
  • string;
  • int, int8, int16, int32, int64;
  • uint, uint8, uint16, uint32, uint64, uintptr;
  • byte = alias for uint8;
  • rune = alias for int32 represents a Unicode code point;
  • float32, float64;
  • complex64, complex128;

The example shows variables of several types, and also that variable declarations may be “factored” into blocks, as with import statements.

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

Zero values

Variables declared without an explicit initial value are given their zero value.

The zero value is:

  • 0 for numeric types,
  • false for the boolean type, and
  • “” (the empty string) for strings.

Composite Structure

In Go a struct is a collection of fields. Each field has a name and a type. Fields are enumerated on different lines. We use struct to define new data types.


Struct fields are accessed using a dot operator “.”

Struct Literals

A struct literal denotes a newly allocated struct value by listing the values of its fields. You can list just a subset of fields by using the “Name:” syntax. The order of named fields is irrelevant. The special prefix & returns a pointer to the struct value.

Pointers to structs

Struct fields can be accessed through a struct pointer.  To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.


In Go arrays are collection of several elements of the same type. Arrays are user defined data types. Notice we do not use keyword array to define an array type instead we define the type  [n]T as an array of n values of type T.

Next expression declares a variable a as an array of ten integers.

Note: 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.


The range is used to create a form of the loop iteration over a slice or a map. When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

Will print:


You can skip the index or value by assigning to “_” If you only want the index, drop the “, value” entirely.

Will print:


slice 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.

In the next example we define an arry “primes” then we create a slice “s” from element 1 (inclusive) to element 4 (inclusive).

Note: Remember the element count start from 0 in Go.

Slices are references

A slice does not store any data, it just describes a section of an underlying array.

Changing the elements of a slice modifies the corresponding elements of its underlying array.

Other slices that share the same underlying array will see those changes.

Slice defaults

When slicing, you may omit the high or low bounds to use their defaults instead.

The default is zero for the low bound and the length of the slice for the high bound.

For the array

these slice expressions are equivalent:

In the next example we use slice defaults to create 3 slices from the same array:

Slice length and capacity

A slice has both a length and a capacity. The length of a slice is the number of elements it contains.

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).

You can extend a slice’s length by re-slicing it, provided it has sufficient capacity.

Nil slices

The zero value of a slice is nil. A nil slice has a length and capacity of 0 and has no underlying array.

Will print:


Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.

The make function allocates a zeroed array and returns a slice that refers to that array:

To specify a capacity, pass a third argument to make:



If executed the program will print:

Compare with Level:

In Level wehn we define something we use a proper English name for it. Here in Go for some unknown reason to create a slice we use make() instead of using slice(). Also the declaration of a slide is very cryptic. We use symbols instead of using a proper keyword name for the slice type. So a slice is not even a type.

Therefore slices are a little bit hard to grasp. Notice that []int is a slice while [0]int is a vector with no elements.


It is common to append new elements to a slice. Go provides a built-in appendfunction. The Go documentation of the built-in package describes append.

The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

(To learn more about slices, read the Slices: usage and internals article.)

Will print:


A map is a data type that is like a table with two columns: key and a value. It is similar to a Python dictionary and sometimes is known as hash table.

Keys of a map can be string or numbers. The value can be any type including user defined type. However in Go all values are of the same type while in Python the values can have different types.

To define a map we use declaration:

var x map[T] type

Where T is a type of the key and type is the type of the values.


nil map has no keys, nor can keys be added to a nil map. This is the zero value of a map.

The make function can be used to create a map of the given type, initialized and ready for use.

Map literals

A map literal is a notation that describe all members of a maps that can be used to initialize a map variable. This literal notation is using nested braces { } to define the collection elements. Map literals are like struct literals  and the keys are required.

If the top-level type is just a type name, you can omit it from the elements of the literal.

Mutating Maps

Insert or update an element in map m:

Retrieve an element:

Delete an element:

Test that a key is present with a two-value assignment:

If key is in “m”, ok is true. If not, ok is false.

If key is not in the map, then elem is the zero value for the map’s element type.

Note: if “elem” or “ok” have not yet been declared you could use a short declaration form:

Program will print:


In Go functions are defined using keyword func. A function can take zero or more arguments declared in enclosed parenthesis after the function name. The arguments have a declared type that comes after the argument name.


Function result

Notice a function can return a result of a particular type. The result type is specified after the list of arguments (…). In the example above the function add has the result type int. The result can be created using the return statement. This is the normal exit point from a function.

Note:When two or more consecutive named function parameters share a type, you can omit the type from all but the last.

A function can return one or multiple results.

Function values

In Go functions can be values and can be assigned to variables. They can be passed around just like other values. Function values may be used as function arguments and return values.


A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variable.

For example, the “adder” function returns a closure. Each closure is bound to its own “sum” variable:


Every Go program is made up of packages. Programs start running in package “main”. The main package also contains the function main(). Using the import statement one package can be used into another package. By convention, the package name is the same as the last element of the import path.

In this instance, th package “math/rand” comprises files that begin with the statement “package rand”.


This code groups the imports into a parenthesis, “factored” import statement.

You can also write multiple import statements, like:

But it is good style to use the factored import statement.

Public elements

In Go, a name is exported if it begins with a capital letter. This is why the println function is using capital P so is fmt.Println. When a package is exported only the capital letter functions and elements are accessible from outside the package.

Note: This convention


Go does not have classes. However Go is object oriented language and has support for creation of objects that have methods and properties.

A method is a function with a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name.

You can define methods on user defined types. These types can be based on collections, structures or simple types.

In next example, the Abs method has a receiver of type Vertex named v. The method can be called using dot notation.

Note I: To create an instance of a type we use define operator “:=” This will define a variable and allocate memory for the new object.

Note II: You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package.


An interface is a type that is like a contract. It define of a set of methods that must be implemented for a type to implement the interface. A value of interface type can hold any value that implements those methods. If one of methods is not implemented you get an error.

Note: There is an error in the example code on line 22. Vertex (the value type) doesn’t implement Abser because the Abs method is defined only on *Vertex (the pointer type).

Empty Interface

The interface type that specifies zero methods is known as the empty interface:

An empty interface may hold values of any type. (Every type implements at least zero methods.)

Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.

Interface Values

Under the covers, interface values can be thought of as a tuple of a value and a concrete type (value, type). An interface value holds a value of a specific underlying concrete type.  Calling a method on an interface value executes the method of the same name on its underlying type.


The following keywords are reserved and may not be used as identifiers.

Operators and punctuation

The following character sequences represent operators (including assignment operators) and punctuation:

See also: Go Lang Specification