Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering Go
Mastering Go

Mastering Go: Leverage Go's expertise for advanced utilities, empowering you to develop professional software , Fourth Edition

eBook
$29.99 $43.99
Paperback
$37.99 $54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Mastering Go

Basic Go Data Types

Data is stored and manipulated in variables—all Go variables should have a data type that is either determined implicitly or declared explicitly. Knowing the built-in data types of Go allows you to understand how to manipulate simple data values and construct more complex data structures when simple data types are not enough or not efficient for a job. Go being a statically typed and compiled programming language allows the compiler to perform various optimizations and checks prior to program execution.

The first part of this chapter is all about the basic data types of Go, and the second part logically follows, covering the data structures that allow you to group data of the same data type, which are arrays and the much more powerful slices.

But let us begin with something more practical: imagine that you want to read data as command line arguments. How can you be sure that what you have read was what you expected? How can you handle error situations...

The error data type

Go provides a special data type, named error, for representing error conditions and error messages—in practice, this means that Go treats errors as values. To program successfully in Go, you should be aware of the error conditions that might occur with the functions and methods you are using and handle them accordingly.

As you already know from the previous chapter, Go follows a particular convention concerning error values: if the value of an error variable is nil, then there is no error. As an example, let us consider strconv.Atoi(), which is used for converting a string value into an int value (Atoi stands for ASCII to Int). As specified by its signature, strconv.Atoi() returns (int, error). Having an error value of nil means that the conversion was successful and that you can use the int value if you want. Having an error value that is not nil means that the conversion was unsuccessful and that the string input is not a valid int value.

...

Numeric data types

Go supports integer, floating-point, and complex number values in various versions depending on the memory space they consume—this saves memory and computing time. Integer data types can be either signed or unsigned, which is not the case for floating-point numbers.

The table that follows lists the numeric data types of Go.

Data Type

Description

int8

8-bit signed integer

int16

16-bit signed integer

int32

32-bit signed integer

int64

64-bit signed integer

int

...

Non-numeric data types

Go has support for strings, characters, runes, dates, and times. However, Go does not have a dedicated char data type. In Go, dates and times are the same thing and are represented by the same data type. However, it is up to you to determine whether a time and date variable contains valid information or not.

We begin by explaining the string-related data types.

Strings, characters, and runes

Go supports the string data type for representing strings—strings are enclosed within either double quotes or back quotes. A Go string is just a collection of bytes and can be accessed as a whole or as an array. A single byte can store any ASCII character—however, multiple bytes are usually needed for storing a single Unicode character.

Nowadays, supporting Unicode characters is a common requirement—Go was designed with Unicode support in mind, which is the main reason for having the rune data type. A rune is an int32 value that is used...

Constants

Go supports constants, which behave like variables but cannot change their values. Constants in Go are defined with the help of the const keyword. Constants can be either global or local. However, if you are defining too many constant values with a local scope, you might need to rethink your approach.

The main benefit you get from using constants in your programs is the guarantee that their value will not change during program execution. Strictly speaking, the value of a constant variable is defined at compile time, not at runtime—this means that it is included in the binary executable. Behind the scenes, Go uses Boolean, string, or numeric as the type for storing constant values because this gives Go more flexibility when dealing with constants.

Some possible uses of constants include defining configuration values such as the maximum number of connections or the TCP/IP port number used and defining physical constants such as the speed of light or the gravity...

Grouping similar data

There are times when you want to keep multiple values of the same data type under a single variable and access them using an index number. The simplest way to do that in Go is by using arrays or slices. Arrays are the most widely used data structures and can be found in almost all programming languages due to their simplicity and speed of access. Go provides an alternative to arrays that is called a slice. The subsections that follow help you understand the differences between arrays and slices so that you know which data structure to use and when. The quick answer is that you can use slices instead of arrays almost anywhere in Go, but we are also demonstrating arrays because they can still be useful and because slices are implemented by Go using arrays!

Arrays

We are going to begin our discussion about arrays by examining their core characteristics and limitations:

  • When defining an array variable, you must define its size. Otherwise, you should...

Pointers

Go has support for pointers but not for pointer arithmetic, which is the cause of many bugs and errors in programming languages like C. A pointer is the memory address of a variable. You need to dereference a pointer in order to get its value—dereferencing is performed using the * character in front of the pointer variable. Additionally, you can get the memory address of a normal variable using an & in front of it.

The next diagram shows the difference between a pointer to an int and an int variable.

A picture containing text, screenshot, rectangle, font  Description automatically generated

Figure 2.4: An int variable and a pointer to an int

If a pointer variable points to an existing regular variable, then any changes you make to the stored value using the pointer variable will modify the regular variable.

The format and the values of memory addresses might be different between different machines, different operating systems, and different architectures.

You might ask, what is the point of using pointers when there...

Data types and the unsafe package

The unsafe package in Go provides facilities for performing operations that break the type safety guarantees of Go. It is a powerful but potentially dangerous package, and its use is discouraged in most Go code. Therefore, the unsafe package is intended for specific situations where low-level programming is necessary, such as interfacing with non-Go code, dealing with memory layout, or implementing certain advanced features.

In this section, we are going to discuss four functions of the unsafe package that are related to strings and slices. You might not have to use any of them on a regular basis, but it is good to know about them because they provide speed when dealing with large strings or slices that take lots of memory because they deal with memory addresses directly, which might be very dangerous if you do not know what you are doing. The four functions that we are going to discuss are unsafe.StringData(), unsafe.String(), unsafe.Slice()...

Generating random numbers

Random number generation is an art as well as a research area in computer science. This is because computers are purely logical machines, and it turns out that using them to generate random numbers is extremely difficult!

Go can help you with that using the functionality of the math/rand package. Each random number generator needs a seed to start producing numbers. The seed is used for initializing the entire process and is extremely important because if you always start with the same seed, you will always get the same sequence of pseudo-random numbers. This means that everybody can regenerate that sequence, and that particular sequence will not be random after all.

However, this feature is very handy for testing purposes. In Go, the rand.Seed() function is used for initializing a random number generator.

If you are really interested in random number generation, you should start by reading the second volume of The Art of Computer Programming...

Updating the statistics application

In this section, we are going to improve the functionality and the operation of the statistics application. When there is no valid input, we are going to populate the statistics application with ten random values, which is pretty handy when you want to put lots of data in an application for testing purposes—you can change the number of random values to fit your needs. However, keep in mind that this takes place when all user input is invalid.

I have randomly generated data in the past in order to put sample data into Kafka topics, RabbitMQ queues and MySQL tables.

Additionally, we are going to normalize the data. Officially, this is called z-normalization and is helpful for allowing sequences of values to be compared more accurately. We are going to use normalization in forthcoming chapters.

The function for the normalization of the data is implemented as follows:

func normalize(data []float64, mean float64, stdDev...

Summary

In this chapter, we learned about the basic data types of Go, including numerical data types, strings, and errors. Additionally, we learned how to group similar values using arrays and slices. Lastly, we learned about the differences between arrays and slices and why slices are more versatile than arrays, as well as pointers and generating random numbers and strings in order to generate random data.

One thing that you should remember from this chapter is that a slice is empty if its length is equal to 0. On the other hand, a slice is nil if it is equal to nil—this means that it points to no memory address. The var s []string statement creates a nil slice without allocating any memory. A nil slice is always empty—the reverse is not always true.

As far as Go strings are concerned, remember that double quotes define an interpreted string literal whereas back quotes define a raw string literal. Most of the time, you need double quotes.

Last, keep in mind...

Exercises

Try to do the following exercises:

  • Correct the error in typedConstants.go.
  • Create and test a function that concatenates two arrays into a new slice.
  • Create a function that concatenates two arrays into a new array. Do not forget to test it with various types of input.
  • Create a function that concatenates two slices into a new array.
  • Run go doc errors Is in order to learn about errors.Is() and try to create a small Go program that uses it. After that, modify error.go to use errors.Is().
  • Modify stats.go in order to accept the number of randomly generated values as a command line argument.
  • Modify stats.go in order to always use randomly generated data.

Additional resources

Join our community on Discord

Join our community’s Discord space for discussions with the authors and other readers:

https://discord.gg/FzuQbc8zd6

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Fully updated with coverage of web services, TCP/IP, REST APIs, Go Generics, and Fuzzy Testing
  • Apply your new knowledge to real-world exercises, building high-performance servers and robust command-line utilities, to deepen your learning
  • Gain clarity on what makes Go different, understand its nuances and features for smoother Go development

Description

Mastering Go, now in its fourth edition, remains the go-to resource for real-world Go development. This comprehensive guide delves into advanced Go concepts, including RESTful servers, and Go memory management. This edition brings new chapters on Go Generics and fuzzy Testing, and an enriched exploration of efficiency and performance. As you work your way through the chapters, you will gain confidence and a deep understanding of advanced Go topics, including concurrency and the operation of the Garbage Collector, using Go with Docker, writing powerful command-line utilities, working with JavaScript Object Notation (JSON) data, and interacting with databases. You will be engaged in real-world exercises, build network servers, and develop robust command-line utilities. With in-depth chapters on RESTful services, the WebSocket protocol, and Go internals, you are going to master Go's nuances, optimization, and observability. You will also elevate your skills in efficiency, performance, and advanced testing. With the help of Mastering Go, you will become an expert Go programmer by building Go systems and implementing advanced Go techniques in your projects.

Who is this book for?

Mastering Go is written primarily for Go programmers who have some experience with the language and want to become expert practitioners. You will need to know the basics of computer programming before you get started with this book, but beyond that, anyone can sink their teeth into it.

What you will learn

  • Learn Go data types, error handling, constants, pointers, and array and slice manipulations through practical exercises
  • Create generic functions, define data types, explore constraints, and grasp interfaces and reflections
  • Grasp advanced concepts like packages, modules, functions, and database interaction
  • Create concurrent RESTful servers, and build TCP/IP clients and servers
  • Learn testing, profiling, and efficient coding for high-performance applications
  • Develop an SQLite package, explore Docker integration, and embrace workspaces

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2024
Length: 736 pages
Edition : 4th
Language : English
ISBN-13 : 9781805122647
Vendor :
Google
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Mar 29, 2024
Length: 736 pages
Edition : 4th
Language : English
ISBN-13 : 9781805122647
Vendor :
Google
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 110.96 149.97 39.01 saved
Mastering Go
$37.99 $54.99
Go Programming - From Beginner to Professional
$32.99 $44.99
50 Algorithms Every Programmer Should Know
$39.98 $49.99
Total $ 110.96 149.97 39.01 saved Stars icon

Table of Contents

17 Chapters
A Quick Introduction to Go Chevron down icon Chevron up icon
Basic Go Data Types Chevron down icon Chevron up icon
Composite Data Types Chevron down icon Chevron up icon
Go Generics Chevron down icon Chevron up icon
Reflection and Interfaces Chevron down icon Chevron up icon
Go Packages and Functions Chevron down icon Chevron up icon
Telling a UNIX System What to Do Chevron down icon Chevron up icon
Go Concurrency Chevron down icon Chevron up icon
Building Web Services Chevron down icon Chevron up icon
Working with TCP/IP and WebSocket Chevron down icon Chevron up icon
Working with REST APIs Chevron down icon Chevron up icon
Code Testing and Profiling Chevron down icon Chevron up icon
Fuzz Testing and Observability Chevron down icon Chevron up icon
Efficiency and Performance Chevron down icon Chevron up icon
Changes in Recent Go Versions Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(24 Ratings)
5 star 79.2%
4 star 20.8%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nilanjan Jun 02, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Learnt a lot, hopefully will help in our current project
Subscriber review Packt
Allen Wyma Apr 08, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently had to use Golang and I was looking to refresh my mind since it's been a few years. I was able to read through this book and it helped me to get a good refreshment of the language and ecosystem since things have changed quite a bit in Golang since I learned it a long time ago.
Amazon Verified review Amazon
Jonathan Reeves Jul 28, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Mastering Go is a one stop shop for being able to learn Go from beginner concepts to advanced and everything in between. If you are looking for an easy to follow and really well written book that will cover all that you need to understand and write Go then look no further. This book is a great resource for Go developers. Whether you are an experienced Go developer or a beginner this book has something in it for you.
Amazon Verified review Amazon
Windsänger
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently had the pleasure of diving into "Mastering Go: Fourth Edition" and it has truly been a game-changer for me. First and foremost, a huge thank you to Vipanshu Parashar for providing me with the reviewing copy!This edition of "Mastering Go" delves into advanced topics like 'Fuzz Testing and Observability' and 'Go Generics', which are crucial for anyone looking to take their Go programming skills to the next level. The authors have done an exceptional job of breaking down complex concepts into digestible chunks, making it accessible for both intermediate and experienced developers.What I particularly appreciated about this book is its practical approach. It not only explains theoretical concepts but also provides real-world examples and hands-on exercises, allowing readers to apply what they've learned in a meaningful way.Whether you're looking to enhance your understanding of Go's concurrency model, optimize performance, or explore the latest features like generics, "Mastering Go: Fourth Edition" has got you covered.Overall, I highly recommend this book to anyone serious about mastering Go programming. It's an invaluable resource that will undoubtedly help you become a more proficient Go developer. Five stars without hesitation!
Amazon Verified review Amazon
Gaurav Apr 09, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Mastering Go, Fourth Edition, is an indispensable resource for any Go programmer looking to deepen their understanding and master advanced topics. This edition covers an array of cutting-edge subjects, including Go Generics and Fuzzy Testing, ensuring it stays relevant in the ever-evolving landscape of Go programming.What sets this edition apart is its comprehensive coverage of crucial topics like concurrency, web services, and testing techniques. From RESTful servers to TCP/IP clients and servers, the book leaves no stone unturned in exploring the nuances of Go development. Additionally, the discussions on efficiency, performance, and observability equip readers with essential skills for optimizing their applications.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.