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ó

Share book
  1. 822 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & 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ó

Book details
Book preview
Table of contents
Citations

About This Book

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is The Go Workshop an online PDF/ePUB?
Yes, you can access The Go Workshop by Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó in PDF and/or ePUB format, as well as other popular books in Computer Science & Open Source Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781838640156
Edition
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...

Table of contents