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.

package main

//import the format package
import "fmt" 

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

Statements

  • 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 “;”

Variables

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.

package main

import "fmt"

var c, python, java bool

func main() {
	var i int
	fmt.Println(i, c, python, java)
}

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.

package main

import "fmt"

var i, j int = 1, 2

func main() {
	var c, python, java = true, false, "no!"
	fmt.Println(i, j, c, python, java)
}

Type inference

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

package main

import "fmt"

func main() {
	var i, j int = 1, 2
	k := 3
	c, python, java := true, false, "no!"

	fmt.Println(i, j, k, c, python, java)
}

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

Constants

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.
package main

import "fmt"

const Pi = 3.14

func main() {
	const World = "世界"
	fmt.Println("Hello", World)
	fmt.Println("Happy", Pi, "Day")

	const Truth = true
	fmt.Println("Go rules?", Truth)
}

Numeric Constants

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

package main

import "fmt"

const (
	// Create a huge number by shifting a 1 bit left 100 places.
	// In other words, the binary number that is 1 followed by 100 zeroes.
	Big = 1 << 100
	// Shift it right again 99 places, so we end up with 1<<1, or 2. Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
	return x * 0.1
}

func main() {
	fmt.Println(needInt(Small))
	fmt.Println(needFloat(Small))
	fmt.Println(needFloat(Big))
}

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;
package main

import (
	"fmt"
	"math/cmplx"
)

var (
	ToBe   bool       = false
	MaxInt uint64     = 1<<64 - 1
	z      complex128 = cmplx.Sqrt(-5 + 12i)
)

func main() {
	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)
}

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.

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	fmt.Println(Vertex{1, 2})
}

 

Struct fields are accessed using a dot operator “.”

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	v := Vertex{1, 2}
	v.X = 4
	fmt.Println(v.X)
}

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.

package main

import "fmt"

type Vertex struct {
	X, Y int
}

var (
	v1 = Vertex{1, 2}  // has type Vertex
	v2 = Vertex{X: 1}  // Y:0 is implicit
	v3 = Vertex{}      // X:0 and Y:0
	p  = &Vertex{1, 2} // has type *Vertex
)

func main() {
	fmt.Println(v1, p, v2, v3)
}

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.

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	v := Vertex{1, 2}
	p := &v
	p.X = 10
	fmt.Println(v) // {10 2}
}

Arrays

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.

var a [10]int

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.

package main

import "fmt"

func main() {
	var a [2]string
	a[0] = "Hello"
	a[1] = "World"
	fmt.Println(a[0], a[1])
	fmt.Println(a)

	primes := [6]int{2, 3, 5, 7, 11, 13}
	fmt.Println(primes)
}

Range

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.

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
	for i, v := range pow {
		fmt.Printf("2**%d = %d\n", i, v)
	}
}

Will print:

2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128

 

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

package main

import "fmt"

func main() {
	pow := make([]int, 10)
	for i := range pow {
		pow[i] = 1 << uint(i) // == 2**i
	}
	for _, value := range pow {
		fmt.Printf("%d\n", value)
	}
}

Will print:

2
4
8
16
32
64
128
256
512

Slices

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

package main

import "fmt"

func main() {
	primes := [6]int{2, 3, 5, 7, 11, 13}

	var s []int = primes[1:4]
	fmt.Println(s) // [3 5 7]
}

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.

package main

import "fmt"

func main() {
	names := [4]string{
		"John",
		"Paul",
		"George",
		"Ringo",
	}
	fmt.Println(names)

	a := names[0:2]
	b := names[1:3]
	fmt.Println(a, b)

	b[0] = "XXX"
	fmt.Println(a, b)
	fmt.Println(names)
}

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

var a [10]int

these slice expressions are equivalent:

a[0:10]
a[:10]
a[0:]
a[:]

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

{2, 3, 5, 7, 11, 13}
package main

import "fmt"

func main() {
	s := []int{2, 3, 5, 7, 11, 13}

	s = s[1:4]
	fmt.Println(s)

	s = s[:2]
	fmt.Println(s)

	s = s[1:]
	fmt.Println(s)
}
[3 5 7]
[3 5]
[5]

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.

package main

import "fmt"

func main() {
	s := []int{2, 3, 5, 7, 11, 13}
	printSlice(s)

	// Slice the slice to give it zero length.
	s = s[:0]
	printSlice(s)

	// Extend its length.
	s = s[:4]
	printSlice(s)

	// Drop its first two values.
	s = s[2:]
	printSlice(s)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

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.

package main

import "fmt"

func main() {
	var s []int
	fmt.Println(s, len(s), cap(s))
	if s == nil {
		fmt.Println("nil!")
	}
}

Will print:

[] 0 0
nil!

Make

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:

a := make([]int, 5)  // len(a)=5

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

b := make([]int, 0, 5) // len(b)=0, cap(b)=5

b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:]      // len(b)=4, cap(b)=4

Example:

package main

import "fmt"

func main() {
	a := make([]int, 5)
	printSlice("a", a)

	b := make([]int, 0, 5)
	printSlice("b", b)

	c := b[:2]
	printSlice("c", c)

	d := c[2:5]
	printSlice("d", d)
}

func printSlice(s string, x []int) {
	fmt.Printf("%s len=%d cap=%d %v\n",
		s, len(x), cap(x), x)
}

 

If executed the program will print:

a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]

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.

Append

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.

func append(s []T, vs ...T) []T

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

package main

import "fmt"

func main() {
	var s []int
	printSlice(s)

	// append works on nil slices.
	s = append(s, 0)
	printSlice(s)

	// The slice grows as needed.
	s = append(s, 1)
	printSlice(s)

	// We can add more than one element at a time.
	s = append(s, 2, 3, 4)
	printSlice(s)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

Will print:

len=0 cap=0 []
len=1 cap=2 [0]
len=2 cap=2 [0 1]
len=5 cap=8 [0 1 2 3 4]

Maps

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.

package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m map[string] Vertex

func main() {
	m = make(map[string] Vertex)
	m["Bell Labs"] = Vertex{
		40.68433, -74.39967,
	}
	fmt.Println(m["Bell Labs"])
}

Notes:

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.

package main

import "fmt"

type Vertex struct {
    Lat, Long float64
}

var m = map[string] Vertex{
    "Bell Labs": Vertex{
        40.68433, -74.39967,
    },
    "Google": Vertex{
        37.42202, -122.08408,
    },
}

func main() {
    fmt.Println(m)
}

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

package main

import "fmt"

type Vertex struct {
    Lat, Long float64
}

var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}

func main() {
    fmt.Println(m)
}

Mutating Maps

Insert or update an element in map m:

m[key] = elem

Retrieve an element:

elem = m[key]

Delete an element:

delete(m, key)

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

elem, ok = m[key]

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:

elem, ok := m[key]
package main

import "fmt"

func main() {
    m := make(map[string]int)

    m["Answer"] = 42
    fmt.Println("The value:", m["Answer"])

    m["Answer"] = 48
    fmt.Println("The value:", m["Answer"])

    delete(m, "Answer")
    fmt.Println("The value:", m["Answer"])

    v, ok := m["Answer"]
    fmt.Println("The value:", v, "Present?", ok)
}

Program will print:

The value: 42
The value: 48
The value: 0
The value: 0 Present? false

Functions

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.

 

package main

import "fmt"

func add(x int, y int) int {
    return x + y
}

func main() {
    fmt.Println(add(42, 13))
}

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.

func add(x, y int) int {
	return x + y
}

A function can return one or multiple results.

package main

import "fmt"

func swap(x, y string) (string, string) {
	return y, x
}

func main() {
	a, b := swap("hello", "world")
	fmt.Println(a, b)
}

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.

package main

import (
	"fmt"
	"math"
)

func compute(fn func(float64, float64) float64) float64 {
	return fn(3, 4)
}

func main() {
	hypot := func(x, y float64) float64 {
		return math.Sqrt(x*x + y*y)
	}
	fmt.Println(hypot(5, 12))

	fmt.Println(compute(hypot))
	fmt.Println(compute(math.Pow))
}

Closures

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:

package main

import "fmt"

func adder() func(int) int {
    sum := 0
    return func(x int) int {
        sum += x
        return sum
    }
}

func main() {
    pos, neg := adder(), adder()
    for i := 0; i < 10; i++ {
        fmt.Println(
            pos(i),
            neg(-2*i),
        )
    }
}

Packages

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.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println("My favorite number is", rand.Intn(10))
}

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

Import

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

You can also write multiple import statements, like:

import "fmt"
import "math"

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

Methods

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.

package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := Vertex{3, 4}
	fmt.Println(v.Abs())
}

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.

Interfaces

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.

package main

import (
	"fmt"
	"math"
)

//define an interface
type Abser interface {
	Abs() float64
}

func main() {
	var a Abser
	
	//define a function f
	f := MyFloat(-math.Sqrt2)
	v := Vertex{3, 4}

	a = f  // a MyFloat implements Abser
	a = &v // a *Vertex implements Abser

	// In the following line, v is a Vertex (not *Vertex)
	// therefore does NOT implement Abser.
	a = v

	fmt.Println(a.Abs())
}

type MyFloat float64

func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}

type Vertex struct {
	X, Y float64
}

func (v *Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

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:

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{}.

package main

import "fmt"

func main() {
	var i interface{}
	describe(i)

	i = 42
	describe(i)

	i = "hello"
	describe(i)
}

func describe(i interface{}) {
	fmt.Printf("(%v, %T)\n", i, i)
}

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.

package main

import (
	"fmt"
	"math"
)

type I interface {
	M()
}

type T struct {
	S string
}

func (t *T) M() {
	fmt.Println(t.S)
}

type F float64

func (f F) M() {
	fmt.Println(f)
}

func main() {
	var i I

	i = &T{"Hello"}
	describe(i)
	i.M()

	i = F(math.Pi)
	describe(i)
	i.M()
}

func describe(i I) {
	fmt.Printf("(%v, %T)\n", i, i)
}

Keywords

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

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

Operators and punctuation

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

+    &     +=    &=     &&    ==    !=    (    )
-    |     -=    |=     ||    <     <=    [    ]
*    ^     *=    ^=     <-    >     >=    {    }
/    <<    /=    <<=    ++    =     :=    ,    ;
%    >>    %=    >>=    --    !     ...   .    :
     &^          &^=

See also: Go Lang Specification