Avatar
José Cintra is a software developer with skills in IoT, databases, WEB and games. He also works as a university professor specialized in the field of algorithms and data structures

Origins

The GO language was developed in 2007 by a Google team led by Robert Griesemer, Rob Pike, and Ken Thompson, and was officially released as open source in November 2009.

The reason for the creation of the new language was to solve some of the problems in the software infrastructure development at Google.

The main characteristics of Go include:

  • Easy to learn. Go’s syntax is small compared to other languages.
  • Go is a strongly, statically typed language, but with support for type inference.
  • Fast Compilation. The compiler of the GO language, besides being fast, produces only one executable file, without dependencies, that can be executed anywhere.
  • Powerful Standard Library and Tool Set. The Go ecosystem has a powerful native library. Also, it offers a wide range of tools that makes development process efficient.
  • Concurrency. This is the strength of the language. Golang has built-in concurrency constructs: goroutines and channels.

Installation

The first step is to download the installation package from the official website. There you will find all installation and configuration instructions: https://golang.org/doc/install

After installing, you must already plan how your Workspace will be set up — that is, where your source code files will live. There is a pattern for this: https://golang.org/doc/gopath_code.html

Here’s an extensive list of IDEs with support for the GO language:
https://github.com/golang/go/wiki/IDEsAndTextEditorPlugins

Program Structure

Let’s create the traditional “Hello World!” example in GO. To do this, open the editor and create a file called hello.go in the folder GOROOT/src/hello and enter the following code:

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

As you can see, unlike C, we don’t use separators like the semicolon at the end of the commands. Let’s see what else we can learn from this example:

Every program must start with the package declaration. In this example, the package’s main tells the compiler that the package should be an executable program instead of a library. It is the starting point of the program and also contains the main function.

The import keyword is used to import packages in your program. The fmt package is a formatting package that implements several text input and output functions.

You also see an example of the main() function in Go. In this case, the function will print the message “Hello World!” using the Println() method from the fmt package.

To compile this program, we use the following command in the folder GOROOT/src/hello:

go build hello.go

To compile and run::

go run hello.go

Program Structure

Let’s take a look at the structural components of writing Go code.

To encourage modularity and organization, every Go program must be part of a package. A package is a collection of source files in the same directory that are compiled together.

To declare a source file as part of a package, we do the following:

package packagename

This package declaration must be the first line of code. In this way, all functions, types, and variables defined in your Go source file become part of that package.

Go has a powerful native library that is also organized into packages. To use one of these libraries, we use the import command, like this:

import "fmt"
import "math"

Data types

The Basic Data Types are categorized into three subcategories which are: Numbers, Booleans, and Strings.

The numeric data types, in turn, are divided between integers, floating points, and complexes, and the integers can be represented with (int) or without sign (uint). In addition, numbers are classified according to precision (8, 16, 32 and 64 bits)

  • Integers: int, int8, uint8, int16, uint16, int32, uint32 , int64, uint64
  • Floating-point: float32, float64
  • Complex: complex64, complex128

The string data type represents an immutable sequence of Unicode characters. This means that once a string is created, you cannot change it.

The Boolean data type represents only one bit of information, true or false. Boolean type values cannot be converted to any other type, as in other languages.

Variables

GO is a strongly typed language. Therefore, all variables must have their types declared before they are used. For this we use the reserved word var.

Optionally, we can assign an initial value to the variable in the declaration (initialization). Variables declared without a corresponding initialization are zero-valued, unlike languages like C.

You can omit the data type in a declaration when you assign an initial value to the variable. The compiler will use type inference based on value of the declaration. There is also a short form of declaration, without using var.

Here are some examples:

var age int8 
var age int8 = 18 
var age = 18 // Type inference
age := 18 // shorthand declaration 

Pointers

Pointers are variables used to store the memory address of another variable. Like in C, the reference operator (&) provides the memory address of a variable, while the dereference operator (*) indicates the contents of the memory address.

The implementation of pointers in GOLANG is done safely, unlike other languages like C, since GO does not support pointer arithmetic.

Data Structures

Golang has a series of classic and modern built-in data structures designed to be efficient and fast. We will see below the main structures available:

Arrays

Like in C, an array is a fixed-length sequence of homogeneous values. Let’s look at some ways to declare an array with 5 integers:

var arr[5] int
var a = [5] int{1,2,3,4,5}
arr := [5] int{1,2,3,4,5}
OR
arr := [...] int{1,2,3,4,.5}

Slices

We can say that a slice is a more flexible array. Slices are indexable and have a length. But unlike arrays, they can be resized.

The slice is declared just like an array except that we do not specify any size:

// Slice of type int
var mySlice []int

// Creating and initializing a slice
var mySlice = []int{3, 5, 7, 9, 11, 13, 17}

// Creating a slice using the make function. 
// The make function expects a type, length and a capacity.
mySlice := make([]int, 5, 10)

To facilitate the handling of slices, there are several functions, such as:

  • copy: copies elements from one slice to another.
  • append: appends new elements at the end of the slice.
  • sort: different types of sorting methods for sorting slices.

Maps

A map is an associative data type, sometimes called a dictionary in other languages. A map has a set of keys and each key has a unique associated value. When requested with a key, the map will return the associated value.

Go provides a built-in map type. To declare a map, simply inform the type of the key and the type of the related value. Here are some examples:

var myMap = map[string]string //Empty map
myMap["Hello"] = "world" //Adding items 
fmt.Println(myMap["Hello"]) // Retrieving the value associated

Structs

A struct is a user-defined data type, composed of a set of fields not necessarily of the same type. For example, we can represent a rectangle as follows:

type Rect struct {
  x float64 // The x-coordinate of the upper-left corner
  y float64 // The y-coordinate of the upper-left corner
  w float64 // The width of the rectangle
  H float64 // The height of the rectangle
}
r := new(Rect) // create a variable of type rect

To initialize the x-coordinate of our rectangle:

r.x = 10

Similarly, we can always access fields by using the dot operator:

fmt.Println(r.x)

Control Structures

GO has only three control structures:

If and Switch

The decision structures if and switch look very much like the C language. The difference is that, in GO, the expression need not be surrounded by parentheses and must result in a Boolean value.

Here’s an example of if:

if num < 0 {
    fmt.Println(num, " is a negative number")
} else if num > 0 {
    fmt.Println(num, " is a positive number")
} else {
    fmt.Println(num, " is zero")
}

And here’s an example of switch:

switch num {
    case 0: 
        fmt.Println("Zero")
    case 1,2:
        fmt.Println("One or Two")
    default:
        fmt.Println("Other")
}

For

Rightly, the for construction is the only repetition structure available in the language. As in other languages derived from C, the for statement is composed of three components separated by semicolons.

Let’s look at this example that calculates the factorial of the number 5:

fatorial := 1
for i := 1; i < 5; i++ {
    fatorial *= i
}
fmt.Println(fatorial)O

Note: The braces are always required.

Functions

Golang is an extremely modular language and functions play an important role in its architecture. Let’s look at an example:

func main() {
   a := 8.0
   b := 2.0
   r,e := div(a,b)
   if e == nil {
       fmt.Println("dividing", a, " by ", b, " is ", r)
   } else {
       fmt.Println("Error: ", e)
   }    
}
func div(a,b float64) (float64, error) {
   if b == 0 {
	   return 0, errors.New("The divider cannot be zero")
   }
   return a/b, nil  	
}

Functions can return multiple values, a good opportunity to return error codes.

In the function call, we can ignore certain return values. For this, we use the blank identifier:

r, _ := div(a,b)

By default, passing parameters is by value. To pass the parameters by reference, we must use pointers through the reference operator (&).

Go supports variadic, anonymous, and first class functions.

Furthermore, GO does not support optional parameters, default parameter values, and overloading.

Variable Scope and Visibility

At this point, it is good to talk about scope and visibility. Golang scope rules of variables can be divided into two categories:

  • Local variables: Declared within a block or function. This includes a for command, for example.
  • Global variables: Declared outside any function

Regarding visibility, unlike other languages such as Java, which use access modifiers such as public, private, or protected to specify visibility, Golang determines whether a member is exported or not exported using its name.

An exported member means that it is visible outside the package where it was declared. This visibility is defined by capitalizing the first letter of the declared member.

Object Orientation

Support for object orientation in GOLANG is a controversial subject. The authors themselves do not firmly state that GO is an object-oriented language.

GO implements the main features of the object-oriented paradigm like encapsulation, information hiding, interfaces, and structs as classes.

However, it does not support inheritance and, consequently, polymorphism. If you’re interested in this complicated subject, take a look at the following articles:

Concurrency with Goroutines

Goroutines are functions that are executed concurrently with other functions. Unlike other languages that use OS threads directly to implement concurrency, a goroutine is a lightweight thread managed by the Go runtime.

To call a function f() as a goroutine, use the reserved word go:

go f()

Goroutines can communicate via messages. Channels are the pipes used for the connection. You can also send and receive values through the channels.

ch := make(chan int)
ch <- m    // Send v to channel ch
m := <-ch  // Receive from ch

See more details in this link: Goroutines – Concurrency in Golang.

To Learn more About Go

I hope this short guide has given you a comprehensive overview of the GO language and encourages you to be part of the growing Gopher Community!

To learn more, the following websites provide useful references and tutorials.

My favorite books on Go are:

  • “The Go Programming Language” by Brian W. Kernighan, Alan A. A. Donovan Publisher: Addison-Wesley Professional
  • “Go in Action” by William Kennedy, Brian Ketelsen, Erik St. Martin
    Publisher: Manning Publications

How to work with us

  • Contact us to set up a call.
  • We will analyze your needs and recommend a content contract solution.
  • Sign on with ContentLab.
  • We deliver topic-curated, deeply technical content to you.

To get started, complete the form to the right to schedule a call with us.

Send this to a friend