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! 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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering Go
Mastering Go

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

Arrow left icon
Profile Icon Mihalis Tsoukalos
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (24 Ratings)
Paperback Mar 2024 736 pages 4th Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Mihalis Tsoukalos
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (24 Ratings)
Paperback Mar 2024 736 pages 4th Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781805127147
Vendor :
Google
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 29, 2024
Length: 736 pages
Edition : 4th
Language : English
ISBN-13 : 9781805127147
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 113.97
50 Algorithms Every Programmer Should Know
€37.99
Go Programming - From Beginner to Professional
€33.99
Mastering Go
€41.99
Total 113.97 Stars icon
Banner background image

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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.