Mastering Go - Second Edition

Book description

Publisher's Note: This edition from 2019 is outdated and is not compatible with the latest version of Go. A new third edition, updated for 2021 and featuring the latest in Go programming, has now been published.

Key Features

  • Second edition of the bestselling guide to advanced Go programming, expanded to cover machine learning, more Go packages and a range of modern development techniques
  • Completes the Go developer's education with real-world guides to building high-performance production systems
  • Packed with practical examples and patterns to apply to your own development work
  • Clearly explains Go nuances and features to remove the frustration from Go development

Book Description

Often referred to (incorrectly) as Golang, Go is the high-performance systems language of the future. Mastering Go, Second Edition helps you become a productive expert Go programmer, building and improving on the groundbreaking first edition.

Mastering Go, Second Edition shows how to put Go to work on real production systems. For programmers who already know the Go language basics, this book provides examples, patterns, and clear explanations to help you deeply understand Go's capabilities and apply them in your programming work.

The book covers the nuances of Go, with in-depth guides on types and structures, packages, concurrency, network programming, compiler design, optimization, and more. Each chapter ends with exercises and resources to fully embed your new knowledge.

This second edition includes a completely new chapter on machine learning in Go, guiding you from the foundation statistics techniques through simple regression and clustering to classification, neural networks, and anomaly detection. Other chapters are expanded to cover using Go with Docker and Kubernetes, Git, WebAssembly, JSON, and more.

If you take the Go programming language seriously, the second edition of this book is an essential guide on expert techniques.

What you will learn

  • Clear guidance on using Go for production systems
  • Detailed explanations of how Go internals work, the design choices behind the language, and how to optimize your Go code
  • A full guide to all Go data types, composite types, and data structures
  • Master packages, reflection, and interfaces for effective Go programming
  • Build high-performance systems networking code, including server and client-side applications
  • Interface with other systems using WebAssembly, JSON, and gRPC
  • Write reliable, high-performance concurrent code
  • Build machine learning systems in Go, from simple statistical regression to complex neural networks

Who this book is for

Mastering Go, Second Edition is for Go programmers who already know the language basics, and want to become expert Go practitioners.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Go Second Edition
  3. About Packt
    1. Why subscribe?
  4. Contributors
    1. About the author
    2. About the reviewer
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Go and the Operating System
    1. The history of Go
    2. Where is Go going?
    3. The advantages of Go
      1. Is Go perfect?
        1. What is a preprocessor?
      2. The godoc utility
    4. Compiling Go code
    5. Executing Go code
    6. Two Go rules
      1. You either use a Go package or you do not include it
      2. There is only one way to format curly braces
    7. Downloading Go packages
    8. UNIX stdin, stdout, and stderr
    9. About printing output
    10. Using standard output
    11. Getting user input
      1. About := and =
      2. Reading from standard input
      3. Working with command-line arguments
    12. About error output
    13. Writing to log files
      1. Logging levels
      2. Logging facilities
      3. Log servers
      4. A Go program that sends information to log files
      5. About log.Fatal()
      6. About log.Panic()
      7. Writing to a custom log file
      8. Printing line numbers in log entries
    14. Error handling in Go
      1. The error data type
      2. Error handling
    15. Using Docker
    16. Exercises and links
    17. Summary
  7. Understanding Go Internals
    1. The Go compiler
    2. Garbage collection
      1. The tricolor algorithm
      2. More about the operation of the Go garbage collector
      3. Maps, slices, and the Go garbage collector
        1. Using a slice
        2. Using a map with pointers
        3. Using a map without pointers
        4. Splitting the map
        5. Comparing the performance of the presented techniques
      4. Unsafe code
      5. About the unsafe package
      6. Another example of the unsafe package
    3. Calling C code from Go
      1. Calling C code from Go using the same file
      2. Calling C code from Go using separate files
      3. The C code
      4. The Go code
      5. Mixing Go and C code
    4. Calling Go functions from C code
      1. The Go package
      2. The C code
    5. The defer keyword
      1. Using defer for logging
    6. Panic and recover
      1. Using the panic function on its own
    7. Two handy UNIX utilities
      1. The strace tool
      2. The dtrace tool
    8. Your Go environment
    9. The go env command
    10. The Go assembler
    11. Node trees
    12. Finding out more about go build
    13. Creating WebAssembly code
      1. A quick introduction to WebAssembly
      2. Why is WebAssembly important?
      3. Go and WebAssembly
      4. An example
      5. Using the generated WebAssembly code
    14. General Go coding advice
    15. Exercises and links
    16. Summary
  8. Working with Basic Go Data Types
    1. Numeric data types
      1. Integers
      2. Floating-point numbers
      3. Complex numbers
      4. Number literals in Go 2
    2. Go loops
      1. The for loop
      2. The while loop
      3. The range keyword
      4. An example with multiple Go loops
    3. Go arrays
      1. Multi-dimensional arrays
      2. The shortcomings of Go arrays
    4. Go slices
      1. Performing basic operations on slices
      2. Slices are expanded automatically
      3. Byte slices
      4. The copy() function
      5. Multi-dimensional slices
      6. Another example with slices
      7. Sorting slices using sort.Slice()
      8. Appending an array to a slice
    5. Go maps
      1. Storing to a nil map
      2. When you should use a map
    6. Go constants
      1. The constant generator iota
    7. Go pointers
      1. Why use pointers?
    8. Times and dates
      1. Working with times
      2. Parsing times
      3. Working with dates
      4. Parsing dates
      5. Changing date and time formats
    9. Measuring execution time
      1. Measuring the operation of the Go garbage collector
    10. Web links and exercises
    11. Summary
  9. The Uses of Composite Types
    1. About composite types
    2. Structures
      1. Pointers to structures
      2. Using the new keyword
    3. Tuples
    4. Regular expressions and pattern matching
      1. Introducing some theory
      2. A simple example
      3. A more advanced example
      4. Matching IPv4 addresses
    5. Strings
      1. What is a rune?
      2. The unicode package
      3. The strings package
    6. The switch statement
    7. Calculating Pi with high accuracy
    8. Developing a key-value store in Go
    9. Go and the JSON format
      1. Reading JSON data
      2. Saving JSON data
      3. Using Marshal() and Unmarshal()
      4. Parsing JSON data
      5. Go and XML
      6. Reading an XML file
      7. Customizing XML output
    10. Go and the YAML format
    11. Additional resources
    12. Exercises and web links
    13. Summary
  10. How to Enhance Go Code with Data Structures
    1. About graphs and nodes
    2. Algorithm complexity
    3. Binary trees in Go
      1. Implementing a binary tree in Go
      2. Advantages of binary trees
    4. Hash tables in Go
      1. Implementing a hash table in Go
      2. Implementing the lookup functionality
      3. Advantages of hash tables
    5. Linked lists in Go
      1. Implementing a linked list in Go
      2. Advantages of linked lists
    6. Doubly linked lists in Go
      1. Implementing a doubly linked list in Go
      2. Advantages of doubly linked lists
    7. Queues in Go
      1. Implementing a queue in Go
    8. Stacks in Go
      1. Implementing a stack in Go
    9. The container package
      1. Using container/heap
      2. Using container/list
      3. Using container/ring
    10. Generating random numbers
      1. Generating random strings
    11. Generating secure random numbers
    12. Performing matrix calculations
      1. Adding and subtracting matrices
      2. Multiplying matrices
      3. Dividing matrices
        1. A tip on finding out the dimensions of an array
    13. Solving Sudoku puzzles
    14. Additional resources
    15. Exercises
    16. Summary
  11. What You Might Not Know About Go Packages and Functions
    1. About Go packages
    2. About Go functions
      1. Anonymous functions
      2. Functions that return multiple values
      3. The return values of a function can be named
      4. Functions with pointer parameters
      5. Functions that return pointers
      6. Functions that return other functions
      7. Functions that accept other functions as parameters
      8. Variadic functions
    3. Developing your own Go packages
      1. Compiling a Go package
      2. Private variables and functions
      3. The init() function
    4. Go modules
      1. Creating and using a Go module
        1. Creating version v1.0.0
        2. Using version v1.0.0
        3. Creating version v1.1.0
        4. Using version v1.1.0
        5. Creating version v2.0.0
        6. Using version v2.0.0
        7. Creating version v2.1.0
        8. Using version v2.1.0
      2. Using two different versions of the same Go module
      3. Where Go stores Go modules
      4. The go mod vendor command
    5. Creating good Go packages
    6. The syscall package
      1. Finding out how fmt.Println() really works
    7. The go/scanner, go/parser, and go/token packages
      1. The go/ast package
      2. The go/scanner package
      3. The go/parser package
      4. A practical example
      5. Finding variable names with a given string length
    8. Text and HTML templates
      1. Generating text output
      2. Constructing HTML output
    9. Additional resources
    10. Exercises
    11. Summary
  12. Reflection and Interfaces for All Seasons
    1. Type methods
    2. Go interfaces
      1. About type assertions
    3. Writing your own interfaces
      1. Using a Go interface
      2. Using switch with interface and data types
    4. Reflection
      1. A simple reflection example
      2. A more advanced reflection example
      3. The three disadvantages of reflection
      4. The reflectwalk library
    5. Object-oriented programming in Go
    6. An introduction to git and GitHub
      1. Using git
        1. The git status command
        2. The git pull command
        3. The git commit command
        4. The git push command
        5. Working with branches
        6. Working with files
        7. The .gitignore file
        8. Using git diff
        9. Working with tags
        10. The git cherry-pick command
    7. Debugging with Delve
      1. A debugging example
    8. Additional resources
    9. Exercises
    10. Summary
  13. Telling a UNIX System What to Do
    1. About UNIX processes
    2. The flag package
    3. The viper package
      1. A simple viper example
      2. From flag to viper
      3. Reading JSON configuration files
      4. Reading YAML configuration files
    4. The cobra package
      1. A simple cobra example
      2. Creating command aliases
    5. The io.Reader and io.Writer Interfaces
      1. Buffered and unbuffered file input and output
    6. The bufio package
    7. Reading text files
      1. Reading a text file line by line
      2. Reading a text file word by word
      3. Reading a text file character by character
      4. Reading from /dev/random
    8. Reading a specific amount of data
    9. The advantages of binary formats
    10. Reading CSV files
    11. Writing to a file
    12. Loading and saving data on disk
    13. The strings package revisited
    14. About the bytes package
    15. File permissions
    16. Handling UNIX signals
      1. Handling two signals
      2. Handling all signals
    17. Programming UNIX pipes in Go
      1. Implementing the cat(1) utility in Go
    18. About syscall.PtraceRegs
    19. Tracing system calls
    20. User ID and group ID
    21. The Docker API and Go
    22. Additional resources
    23. Exercises
    24. Summary
  14. Concurrency in Go – Goroutines, Channels, and Pipelines
    1. About processes, threads, and goroutines
      1. The Go scheduler
      2. Concurrency and parallelism
    2. Goroutines
      1. Creating a goroutine
      2. Creating multiple goroutines
    3. Waiting for your goroutines to finish
      1. What if the number of Add() and Done() calls do not agree?
    4. Channels
      1. Writing to a channel
      2. Reading from a channel
      3. Receiving from a closed channel
      4. Channels as function parameters
    5. Pipelines
    6. Race conditions
    7. Comparing Go and Rust concurrency models
    8. Comparing Go and Erlang concurrency models
    9. Additional resources
    10. Exercises
    11. Summary
  15. Concurrency in Go – Advanced Topics
    1. The Go scheduler revisited
      1. The GOMAXPROCS environment variable
    2. The select keyword
    3. Timing out a goroutine
      1. Timing out a goroutine – take 1
      2. Timing out a goroutine – take 2
    4. Go channels revisited
      1. Signal channels
      2. Buffered channels
      3. Nil channels
      4. Channels of channels
      5. Specifying the order of execution for your goroutines
      6. How not to use goroutines
    5. Shared memory and shared variables
      1. The sync.Mutex type
        1. What happens if you forget to unlock a mutex?
      2. The sync.RWMutex type
      3. The atomic package
      4. Sharing memory using goroutines
    6. Revisiting the go statement
    7. Catching race conditions
    8. The context package
      1. An advanced example of the context package
      2. Another example of the context package
      3. Worker pools
    9. Additional resources
    10. Exercises
    11. Summary
  16. Code Testing, Optimization, and Profiling
    1. About optimization
    2. Optimizing Go code
    3. Profiling Go code
      1. The net/http/pprof standard Go package
      2. A simple profiling example
      3. A convenient external package for profiling
      4. The web interface of the Go profiler
        1. A profiling example that uses the web interface
        2. A quick introduction to Graphviz
    4. The go tool trace utility
    5. Testing Go code
      1. Writing tests for existing Go code
      2. Test code coverage
    6. Testing an HTTP server with a database backend
      1. The testing/quick package
        1. What if testing takes too long or never finishes?
    7. Benchmarking Go code
    8. A simple benchmarking example
      1. Wrongly defined benchmark functions
    9. Benchmarking buffered writing
    10. Finding unreachable Go code
    11. Cross-compilation
    12. Creating example functions
    13. From Go code to machine code
      1. Using assembly with Go
    14. Generating documentation
    15. Using Docker images
    16. Additional resources
    17. Exercises
    18. Summary
  17. The Foundations of Network Programming in Go
    1. About net/http, net, and http.RoundTripper
      1. The http.Response type
      2. The http.Request type
      3. The http.Transport type
    2. About TCP/IP
    3. About IPv4 and IPv6
    4. The nc(1) command-line utility
    5. Reading the configuration of network interfaces
    6. Performing DNS lookups
      1. Getting the NS records of a domain
      2. Getting the MX records of a domain
    7. Creating a web server in Go
      1. Using the atomic package
      2. Profiling an HTTP server
      3. Creating a website in Go
    8. HTTP tracing
      1. Testing HTTP handlers
    9. Creating a web client in Go
      1. Making your Go web client more advanced
    10. Timing out HTTP connections
      1. More information about SetDeadline
      2. Setting the timeout period on the server side
      3. Yet another way to time out
    11. The Wireshark and tshark tools
    12. gRPC and Go
      1. Defining the interface definition file
      2. The gRPC client
      3. The gRPC server
    13. Additional resources
    14. Exercises
    15. Summary
  18. Network Programming – Building Your Own Servers and Clients
    1. Working with HTTPS traffic
      1. Creating certificates
      2. An HTTPS client
      3. A simple HTTPS server
      4. Developing a TLS server and client
    2. The net standard Go package
    3. A TCP client
      1. A slightly different version of the TCP client
    4. A TCP server
      1. A slightly different version of the TCP server
    5. A UDP client
    6. Developing a UDP server
    7. A concurrent TCP server
      1. A handy concurrent TCP server
    8. Creating a Docker image for a Go TCP/IP server
    9. Remote Procedure Call (RPC)
      1. The RPC client
      2. The RPC server
    10. Doing low-level network programming
      1. Grabbing raw ICMP network data
    11. Additional resources
    12. Exercises
    13. Summary
  19. Machine Learning in Go
    1. Calculating simple statistical properties
    2. Regression
      1. Linear regression
      2. Implementing linear regression
      3. Plotting data
    3. Classification
    4. Clustering
    5. Anomaly detection
    6. Neural networks
    7. Outlier analysis
    8. Working with TensorFlow
    9. Talking to Kafka
    10. Additional resources
    11. Exercises
    12. Summary
    13. Where to go next?
  20. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Mastering Go - Second Edition
  • Author(s): Mihalis Tsoukalos
  • Release date: August 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781838559335