The Go Workshop
eBook - ePub

The Go Workshop

A New, Interactive Approach to Learning Go

Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó

Compartir libro
  1. 822 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

The Go Workshop

A New, Interactive Approach to Learning Go

Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Get started with Go and learn how to leverage its simplicity and flexibility to solve real-world problems and build practical software

Key Features

  • Build a comprehensive foundation in Go and focus on developing real-world applications
  • Explore the Go Standard Library and learn how to structure your code
  • Learn how to efficiently interact with files, databases and REST APIs

Book Description

The Go Workshop will take the pain out of learning the Go programming language (also known as Golang). It is designed to teach you to be productive in building real-world software. Presented in an engaging, hands-on way, this book focuses on the features of Go that are used by professionals in their everyday work.

Each concept is broken down, clearly explained, and followed up with activities to test your knowledge and build your practical skills.

Your first steps will involve mastering Go syntax, working with variables and operators, and using core and complex types to hold data. Moving ahead, you will build your understanding of programming logic and implement Go algorithms to construct useful functions.

As you progress, you'll discover how to handle errors, debug code to troubleshoot your applications, and implement polymorphism using interfaces. The later chapters will then teach you how to manage files, connect to a database, work with HTTP servers and REST APIs, and make use of concurrent programming.

Throughout this Workshop, you'll work on a series of mini projects, including a shopping cart, a loan calculator, a working hours tracker, a web page counter, a code checker, and a user authentication system.

By the end of this book, you'll have the knowledge and confidence to tackle your own ambitious projects with Go.

What you will learn

  • Understand Go syntax and use it to handle data and write functions
  • Debug your Go code to troubleshoot development problems
  • Safely handle errors and recover from panics
  • Implement polymorphism by using interfaces
  • Work with files and connect to external databases
  • Create a HTTP client and server and work with a RESTful web API
  • Use concurrency to design software that can multitask
  • Use Go Tools to simplify development and improve your code

Who this book is for

The Go Workshop is designed for anyone who is new to Go. Whether you're beginning your journey as an aspiring developer, or are experienced with another programming language and want to branch out to something new, this book will get you on the right track. No prior programming experience is necessary.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es The Go Workshop un PDF/ePUB en línea?
Sí, puedes acceder a The Go Workshop de Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó en formato PDF o ePUB, así como a otros libros populares de Computer Science y Open Source Programming. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2019
ISBN
9781838640156
Edición
1

1. Variables and Operators

Overview
In this chapter, you will be introduced to features of Go and will gain a basic understanding of what Go code looks like. You will also be provided with a deep understanding of how variables work and will perform exercises and activities to get hands-on and get going.
By the end of this chapter, you will be able to use variables, packages, and functions in Go. You will learn to change variable values in Go. Later in the chapter you will use operators with numbers and design functions using pointers.

Introduction

Go (or golang as it's often called) is a programming language popular with developers because of how rewarding it is to use to develop software. It's also popular with companies because teams of all sizes can be productive with it. Go has also earned a reputation for consistently delivering software with exceptionally high performance.
Go has an impressive pedigree since it was created by a team from Google with a long history of building great programming languages and operating systems. They created a language that has the feel of a dynamic language such as JavaScript or PHP but with the performance and efficiency of strongly typed languages such as C++ and Java. They wanted a language that was engaging for the programmer but practical in projects with hundreds of developers.
Go is packed with interesting and unique features, such as being complied with memory safety and channel-based concurrency. We'll explore these features in this chapter. By doing so, you'll see that their unique implementation within Go is what makes Go truly special.
Go is written in text files that are then compiled down to machine code and packaged into a single, standalone executable file. The executable is self-contained, with nothing needed to be installed first to allow it to run. Having a single file makes deploying and distributing Go software hassle-free. When compiling, you can pick one of several target operating systems, including but not limited to Windows, Linux, macOS, and Android. With Go, you write your code once and run it anywhere. Complied languages fell out of favor because programmers hated long waits for their code to compile. The Go team knew this and built a lightning-fast compiler that remains fast as projects grow.
Go has a statically typed and type-safe memory model with a garbage collector. This combination protects developers from creating many of the most common bugs and security flaws found in software while still providing excellent performance and efficiency. Dynamically typed languages such as Ruby and Python have become popular in part because programmers felt they could be more productive if they didn't have to worry about types and memory. The downside of these languages is that they gave up performance and memory efficiency and can be more prone to type-mismatch bugs. Go has the same levels of productivity as dynamically typed languages while not giving up performance and efficiency.
A massive shift in computer performance has taken place. Going fast now means you need to be able to do as much work parallel or concurrently as possible. This change is due to the design of modern CPUs, which emphasize more cores over high clock speed. None of the currently popular programming languages have been designed to take advantage of this fact, which makes writing parallel and concurrent code in them error-prone. Go is designed to take advantage of multiple CPU cores, and it removes all the frustration and bug-filled code. Go is designed to allow any developer to easily and safely write parallel and concurrent code that enables them to take advantage of modern multicore CPUs and cloud computing unlocking high-performance processing and massive scalability without the drama.

What Does Go Look Like?

Let's take our first look at some Go code. This code randomly prints a message to the console from a pre-defined list of messages:
package main
// Import extra functionality from packages
import (
"errors"
"fmt"
"log"
"math/rand"
"strconv"
"time"
)// Taken from: https://en.wiktionary.org/wiki/Hello_World#Translations
var helloList = []string{
"Hello, world",
"Καλημέρα κόσμε",
"こんにちは世界",
"سلام دنیا‎",
"Привет, мир",
}
The main() function is defined as:
func main() {
// Seed random number generator using the current time
rand.Seed(time.Now().UnixNano())
// Generate a random number in the range of out list
index := rand.Intn(len(helloList))
// Call a function and receive multiple return values
msg, err := hello(index)
// Handle any errors
if err != nil {
log.Fatal(err)
}
// Print our message to the console
fmt.Println(msg)
}
Let's consider the hello() function:
func hello(index int) (string, error) {
if index < 0 || index > len(helloList)-1 {
// Create an error, convert the int type to a string
return "", errors.New("out of range: " + strconv.Itoa(index))
}
return helloList[index], nil
}
Now, let's step through this code piece by piece.
At the top of our script is the following:
package main
This code is our package declaration. All Go files must start with one of these. If you want to run the code directly, you'll need to name it main. If you don't name it main, then you can use it as a library and import it into other Go code. When creating an importable package, you c...

Índice