🚀 Think you’ve got what it takes for a career in Data? Find out in just one minute!

An Introduction to Golang development

-
4
 m de lecture
-

Golang, often simply referred to as Go, is an open-source programming language developed by Google and released in 2009. Crafted by Robert Griesemer, Rob Pike, and Ken Thompson, this language is designed to provide a fast, efficient, and easily maintainable solution for modern software development, particularly in the realms of distributed systems, cloud, and back-end infrastructures.

The three creators of Go, from left to right: Robert Griesemer, Rob Pike, and Ken Thompson

Which application domains is it suited for?

The Go language holds particular appeal in various domains, notably:

  • Cloud and distributed systems: Go is often employed in cloud computing environments, where it is especially appreciated for cloud-native applications and microservices.
  • Back-end infrastructures: As a highly performant compiled language, Go is an excellent choice for the back-end of large-scale platforms, such as data management systems and APIs.
  • Web services: Numerous companies utilize it to create Go programs that are both reliable and scalable, like Docker or Kubernetes.

What are its advantages and disadvantages?

Golang provides numerous advantages, yet it also has disadvantages that are important to weigh.

Advantages

Disadvantages

Simplicity: Its syntax is direct, clear, and easy to read.

Lack of generics: Up until recently, Go did not support generics, which could complicate the handling of some data structures.

High performance: As a compiled language, Go is quick in execution, rivaling the performance levels of C or C++.

Primitive syntax: Its simplicity can have downsides. For instance, the language lacks certain advanced abstractions present in other languages.

Concurrency management: Goroutines offer a powerful mechanism for effective and simple concurrency.

Error handling: Error handling is deliberately verbose, potentially making Go code longer and harder to read.

Cross-compilation: Go simplifies the process of compiling source code for multiple platforms.

Rich library ecosystem: It possesses a robust ecosystem of libraries and tools.

What is the structure of the language?

Go’s syntax is relatively similar to that of C.

Packages

A package is a unit of modularity and distribution. Every Go file is associated with a package, and packages enable code to be reused in a structured manner.

  • package main: This specific package designates the entry point of an executable program. If you’re developing an application, it must incorporate the main package.
  • Other packages can be imported to provide additional functionalities, like fmt for handling input/output.

Imports

Imports in Go facilitate the use of external packages or those from the standard library to enhance your program’s features.

For instance, the following code imports a package (fmt) from the standard library:

				
					import "fmt"
				
			

Multiple imports can be declared as follows:

				
					import (
    "fmt"
    "time"
)

				
			

Functions

Functions in Go are blocks of code designed to complete specific tasks. The main function is compulsory as it represents the starting point of any Go program.

The following function, named Hello, takes a name as a parameter and returns a greeting:

				
					func hello(name string) string {
    return "Hello, " + name
}
				
			

Variables

Variables are declared using the var keyword, but they can also be defined more concisely using the := operator for implicit declaration.

The following example demonstrates a first variable explicitly declared as a string, and a second implicitly declared as an integer.

				
					var message string = "Hello World!"
nombre := 42
				
			

Typing

Go is a statically typed language: each variable is determined at compile time.

Control flow

In Go, control flow includes classic constructs like if…else, for and switch. However, it doesn’t have a while loop, although for can serve a similar purpose.

Here, the loop prints numbers from 0 to 9:

				
					for i := 0; i < 10; i++ {
    fmt.Println(i)
}
				
			

The following if statement indicates whether the number is even or odd:

				
					number := 7
if number%2 == 0 {
    fmt.Println("The number is even")
} else {
    fmt.Println("The number is odd")
}
				
			

The following switch statement evaluates the value in the variable day and executes the corresponding block:

				
					day := "tuesday"
switch day {
case "monday":
    fmt.Println("Start of the week")
case "tuesday":
    fmt.Println("Second day of the week")
case "wednesday":
    fmt.Println("Middle of the week")
default:
    fmt.Println("Day not specified")
}
				
			

Data structures

There are several possible data structures, such as arrays, slices, maps, and structs.

  • Slices allow for flexible handling of data sequences:
				
					numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
				
			
  • Maps are a collection of key-value pairs, akin to dictionaries in other languages:
				
					capitals := map[string]string{"France": "Paris", "Italy": "Roma"}
fmt.Println(capitals["France"])
				
			

Basic commands

Golang includes several basic commands that facilitate the management and execution of code:

  • go fmt: Automatically formats Go code for improved readability.
  • go run: Compiles and runs Go code directly.
  • go test: Provides an integrated framework for writing and executing unit tests.
  • go build: Compiles the source code to produce an executable.
				
					capitals := map[string]string{"France": "Paris", "Italy": "Roma"}
fmt.Println(capitals["France"])
				
			

What are Goroutines?

One of Go’s most powerful features is its ability to manage concurrency with goroutines. These are functions that run concurrently with the main program. To start a goroutine, simply prefix a function call with the go keyword.

Here is an example:

				
					package main

import (
    "fmt"
    "time"
)

func worker(mytask string) {
    for i := 0; i < 3; i++ {
        fmt.Printf("%s : iteration %d\n", mytask, i)
        time.Sleep(500 * time.Millisecond)
    }
}

func main() {
    go worker("Task1")
    go worker("Task2")
    worker("Main task")

    // Waiting for goroutine to end
    time.Sleep(2 * time.Second)
}
				
			

The goroutines Task1 and Task2 operate simultaneously with Main task.

Conclusion

Golang is a robust language. Its straightforwardness, efficient concurrency management via goroutines, and the quality of its tools and libraries make it an appealing option for a wide range of modern projects.

Facebook
Twitter
LinkedIn

DataScientest News

Sign up for our Newsletter to receive our guides, tutorials, events, and the latest news directly in your inbox.

You are not available?

Leave us your e-mail, so that we can send you your new articles when they are published!
icon newsletter

DataNews

Get monthly insider insights from experts directly in your mailbox