Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
€22.99 €32.99
Paperback
€28.99 €41.99
Subscription
Free Trial
Renews at €18.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
€18.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
€189.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
€264.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 83.97 113.97 30.00 saved
Mastering Go
€28.99 €41.99
Go Programming - From Beginner to Professional
€24.99 €33.99
50 Algorithms Every Programmer Should Know
€29.99 €37.99
Total 83.97 113.97 30.00 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

Most Recent
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
Most Recent

Filter reviews by




Chad M. Crowell Sep 28, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a thick book, but good for examples and historical context.- I like how the books starts out with solid examples and a learn by example approach- I appreciate the author mentioning his personal preference, and explains why. This shows how opinion-based writing works well for memory and learning- implementing simple versions of traditional UNIX utilities.- the book is organized very well which makes it easy to use for reference as well as for reading from cover to cover- the philosophy and history or golang was really interesting to read about- The exercises at the end of the chapter were really helpful for driving home the concepts.- it drives home the concepts with examples, which is good since you need to see it in real life before you can really understandMy favorite chapter was chapter 12. I would recommend this book. Still not sure why garbage collection is relegated to the appendix, but that's ok.
Amazon Verified review Amazon
Engin Polat Aug 09, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recently finished reading the book and I must say, this is a valuable resource for anyone looking to deepen their understanding of Go.Mastering Go book has both theoretical concepts and practical applications. This makes it ideal for developers who already have a solid foundation in Go and want to take their skills to the next level.What I appreciated most about this edition is how it dives into advanced topics like concurrency patterns, network programming, and performance tuning with clarity and precision. The examples are well-thought-out and demonstrate real-world scenarios, which helped me to immediately apply what I learned to my projects.Additionally, the book is very well structured, making it easy to follow. The updated content reflects the latest developments in the Go ecosystem, making the content is relevant and up-to-date.Overall, "Mastering Go - Fourth Edition" is a must-have for any serious Go developer. Whether you're aiming to build high-performance applications or simply want to master the language, this book will undoubtedly serve as an essential part of your library.
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
Shanthababu Pandian Jul 13, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Learning a new programming language is always exciting for good programmers. Yes, I, too, feel the same way. The market's latest and leading programming language is Go, with its practical applications reshaping the tech industry. Its relevance and potential are something every tech enthusiast should explore!With unparalleled expertise, the authors have meticulously structured the topics into fifteen chapters.This ensures that we're never lost in the learning process and always feel confident in our understanding. The comprehensive breakdown of the chapters keeps us well-informed about the book's content, instilling a sense of trust in the author's guidance.The first five chapters discuss fundamental concepts such as the history of Go and its advantages, how to format, apply coding rules, and compile techniques, find similarities with a scripting language, understand the control programme flow, print output and get user input, work with command-line arguments, write to a custom log file, and use log files. There is an excellent note on “When to use Go language.” It is a must-read.New learners will appreciate a detailed description of basic and composite data types, such as numeric and non-numeric, arrays, pointers, constants, working with dates and times, maps, structures, regular expressions, pattern matching, and classic examples.The separate chapters for generics, reflection, and interface aspects are fantastic. He helps the learners write generic functions and define generic data types, giving them a crystal-clear understanding of the sort interface and how it is used to sort slices and comparison of generics with interfaces and reflection.The author provides precise chapters for packages and functions, including package modules, followed by this discussion of goroutines, channels, and pipelines.I want to highlight chapter seven, “Telling a UNIX System What to Do,” which is fabulous for connecting the dots using the Go language, such as playing with file I/O and packages (viper and Cobra).While this book focuses on goroutines, the author also covers processes, threads, and the Go scheduler and helps learners build web servers and web services and how to create web clients. While dealing with web services, protocols are essential, and we can see how they work with TCP/IP, WebSocket, TCP/IP, and TCP and UDP protocols.When we encounter these web services, REST APIs unquestionably emerge as an advancement in technology. The author helps us define REST APIs and develop powerful concurrent RESTful servers and command-line utilities that act as clients for RESTful services.Regarding the testing aspects, the author brings code testing and profiling, fuzzy testing, and observability in every detail.Although the programme has many features, we must consider the efficiency and performance of the language in the production system; the author discusses benchmarking Go code, understanding the Go memory model, and how to eliminate memory leaks and improve observability, security, and performance in modern Linux systems.One of the significant things I would like to convey here is that the author is building the statistics application from chapter one and improvising the same with features that we are grabbing and understanding for every chapter, enhancing the application and making a sensible approach for learners to apply the concepts on the spot and move on.Overall … I can give 4.5/5.0 for this. Indeed, an extraordinary effort from the author is much appreciated.-Shanthababu PandianAI and Data Architect | Scrum Master | National and International Speaker | Blogger | Author
Amazon Verified review Amazon
hakan Jun 07, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Please add this book to search with language:go.
Subscriber review Packt
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.